package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.enums.ReachTypeEnum;
import com.xmy.cultivate.enums.ReadingStatusEnum;
import com.xmy.cultivate.enums.StatusRecordEnum;
import com.xmy.cultivate.enums.StatusSchedulingEnum;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.feign.math.IMathematicsFeignClient;
import com.xmy.cultivate.feign.physics.IPhysicsFeignClient;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * <p>
 * 记止课 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2022-08-10
 */
@Service
public class RecordCourseServiceImpl extends ServiceImpl<RecordCourseMapper, RecordCourse> implements IRecordCourseService {

    @Autowired
    IdWorker idWorker;

    @Autowired
    @Lazy
    ICourseSchedulingDetailService iCourseSchedulingDetailService;

    @Autowired
    @Lazy
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    IGradeService iGradeService;

    @Autowired
    @Lazy
    IStaffService iStaffService;

    @Autowired
    @Lazy
    IClassRoomService iClassRoomService;

    @Autowired
    ISubjectsService iSubjectsService;

    @Autowired
    @Lazy
    RecordCourseMapper recordCourseMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    IOrderCoursePricingService iOrderCoursePricingService;

    @Autowired
    @Lazy
    IRecordCostService iRecordCostService;

    @Autowired
    @Lazy
    IStudentGradeService iStudentGradeService;


    @Autowired
    @Lazy
    IRecordErrorService iRecordErrorService;

    @Autowired
    @Lazy
    IStudentGradeTemporaryService iStudentGradeTemporaryService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    StudentMapper studentMapper;

    @Autowired
    @Lazy
    IWecharsBindService iWecharsBindService;

    @Autowired
    @Lazy
    IRecordCourseTempService iRecordCourseTempService;

    @Autowired
    @Lazy
    CoursePricingMapper coursePricingMapper;

    @Autowired
    @Lazy
    RepairCourseMapper repairCourseMapper;

    @Autowired
    @Lazy
    OrganizationMapper organizationMapper;

    @Autowired
    @Lazy
    IRecordCourseLackService iRecordCourseLackService;

    @Autowired
    @Lazy
    RecordCourseLackMapper recordCourseLackMapper;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    ILackCourseLogService iLackCourseLogService;

    @Autowired
    @Lazy
    IStudentLeaveApplyService studentLeaveApplyService;

    @Autowired
    IRecordBackDateSetService iRecordBackDateSetService;

    @Autowired
    IMathematicsFeignClient iMathematicsFeignClient;

    @Autowired
    IPhysicsFeignClient iPhysicsFeignClient;

    @Autowired
    IMqPushService iMqPushService;

    /**
     * 批量添加记上课
     *
     * @return
     */
    @Transactional
    public boolean batchAdd(CourseSchedulingDetail courseSchedulingDetail) {

        CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(courseSchedulingDetail.getId());
        if (courseSchedulingDetailInfo == null) {
            throw new CommonException(ResultCode.CourseScheduling);
        }

        List<RecordCourse> recordCourseList = new ArrayList<>();
        Iterator<RecordCourse> recordCourseIterator = courseSchedulingDetail.getRecordCourseList().iterator();

        //临时学员
        List<RecordCourseTemp> recordCourseTempList = new ArrayList<>();

        while (recordCourseIterator.hasNext()) {

            RecordCourse recordCourse = recordCourseIterator.next();

            Student student = studentMapper.selectById(recordCourse.getStudentId());

            if (student == null) {
                continue;
            }

            QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scheduling_detail_id", courseSchedulingDetail.getId());
            queryWrapper.eq("student_id", recordCourse.getStudentId());
            queryWrapper.eq("status", 1);
            Long count = recordCourseMapper.selectCount(queryWrapper);
            if (count > 0) {
                RecordError recordError = new RecordError();
                recordError.setRecordCourseId(recordCourse.getId());
                recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                recordError.setStudentId(recordCourse.getStudentId());
                recordError.setContent("此学生：" + student.getName() + ",已扣过课时，不要重复扣课时");
                iRecordErrorService.save(recordError);
                continue;
            }


            //设置id
            Long recordCourseId = idWorker.nextId();
            recordCourse.setId(recordCourseId);

            //老师
            recordCourse.setTeacherId(courseSchedulingDetailInfo.getTeacherId());
            Staff staff = iStaffService.getById(courseSchedulingDetailInfo.getTeacherId());
            if (staff == null) {
                throw new CommonException(ResultCode.TeacerNo);
            }
            if (staff.getIsTeacher() != 1) {
                throw new CommonException(ResultCode.NotATeacher);
            }
            recordCourse.setTeacherName(staff.getName());

            recordCourse.setSchedulingDetailId(courseSchedulingDetailInfo.getId());
            //校区
            recordCourse.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
            Organization organization = iOrganizationService.getById(courseSchedulingDetailInfo.getSchoolId());
            if (organization != null) {
                recordCourse.setSchoolName(organization.getName());
            }
            //班级
            recordCourse.setGradeId(courseSchedulingDetailInfo.getGradeId());
            /*Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());

            if(grade==null){
                throw new CommonException(ResultCode.CourseSchedulingClassNo);
                //recordCourse.setTeacherGetHouse(grade.getStuDeductHour());//等确定
            }
            Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                throw new CommonException(ResultCode.COURSE_NOT);
            }*/

            Long courseId = null;
            String courseName = "";
            Integer yearClassId = 0;
            if (courseSchedulingDetailInfo.getGradeId() != null) {
                Course course = iCourseService.getById(courseSchedulingDetailInfo.getGradeId());
                if (course != null) {
                    courseId = course.getId();
                    courseName = course.getName();
                    yearClassId = course.getYearClassId().getKey();
                }
            }

            //年份与月份
            Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());

            recordCourse.setYearAndQuarter(yearAndQuarter);
            recordCourse.setYearPart(courseSchedulingDetailInfo.getYearPart());
            recordCourse.setQuarter(courseSchedulingDetailInfo.getQuarter());

            recordCourse.setGradeName(courseSchedulingDetailInfo.getGradeName());
            recordCourse.setCourseId(courseId);
            recordCourse.setCourseName(courseName);
            recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
            recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
            recordCourse.setTimeStart(courseSchedulingDetailInfo.getTimeStart());
            recordCourse.setTimeEnd(courseSchedulingDetailInfo.getTimeEnd());

            //教室
            recordCourse.setClassRoomId(courseSchedulingDetailInfo.getClassRoomId());
            ClassRoom classRoom = iClassRoomService.getById(courseSchedulingDetailInfo.getClassRoomId());
            if (classRoom != null) {
                recordCourse.setClassRoomName(classRoom.getName());
            }
            //科目
            recordCourse.setSubjectsId(courseSchedulingDetailInfo.getSubjectsId());
            Subjects subjects = iSubjectsService.getById(courseSchedulingDetailInfo.getSubjectsId());
            if (subjects != null) {
                recordCourse.setSubjectsName(subjects.getName());
            }


            //扣多少个课时
            Integer buckleClassHouse = recordCourse.getBuckleClassHouse();

            //System.out.print("buckleClassHouse:"+buckleClassHouse);

            //不管是到课，还是请假，都扣课时
            if (recordCourse.getStatus() != null) {
                //到课才扣课时
                if (recordCourse.getStatus().getKey().equals(1)) {//||recordCourse.getStatus().getKey().equals(2)||recordCourse.getStatus().getKey().equals(3)
                    //获取所在班级的最后信息
                    //FirstSignUp firstSignUp = orderDetailMapper.getFirstSignUp(recordCourse.getStudentId(),courseSchedulingDetailInfo.getGradeId(),buckleClassHouse);

                    Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(courseSchedulingDetailInfo.getSchoolId(), recordCourse.getStudentId(), courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType(),recordCourse.getYearClassId());
                    //System.out.println("residueCourseCount:"+residueCourseCount);
                    //获取剩余课时
                    //OrderDetailTiny orderDetailTiny = orderDetailMapper.getResidueCourseCountForCourseId(recordCourse.getStudentId(),recordCourse.getCourseId(),recordCourse.getSchoolId());


                    if (residueCourseCount < buckleClassHouse) {
                        RecordError recordError = new RecordError();
                        recordError.setRecordCourseId(recordCourse.getId());
                        recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                        recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                        recordError.setStudentId(recordCourse.getStudentId());
                        recordError.setContent("此学生：" + student.getName() + ",课程：" + courseName + "剩余课时不足：" + buckleClassHouse);
                        iRecordErrorService.save(recordError);
                        //此学生该课程没有可用课时
                        continue;
                    }

                    List<OrderDetail> orderDetailList = orderDetailMapper.orderDetailListForSubjects(recordCourse.getSchoolId(), recordCourse.getStudentId(), courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType(),yearClassId);

                    Integer diffClassHosue = buckleClassHouse;//还差多少课时

                    BigDecimal teaGainHourAll = new BigDecimal(0);//老师得课时总课时
                    BigDecimal teaGainMoneyAll = new BigDecimal(0);

                    BigDecimal buckleClassMoneyAll = new BigDecimal(0);
                    BigDecimal buckleClassHourAll = new BigDecimal(0);

                    for (OrderDetail orderDetail : orderDetailList) {
                        if (diffClassHosue == 0) {
                            continue;
                        }
                        CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
                        if (coursePricing == null) {
                            //此学生数据异常
                            RecordError recordError = new RecordError();
                            recordError.setRecordCourseId(recordCourse.getId());
                            recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                            recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                            recordError.setStudentId(recordCourse.getStudentId());
                            recordError.setContent("此学生课程价格数据异常：" + orderDetail.getCoursePriceId());
                            iRecordErrorService.save(recordError);
                            continue;
                        }

                        Integer userClassHouse = 0;//本次使用课时
                        //本次要扣的课时大于等于剩余课时
                        if (diffClassHosue > orderDetail.getResidueCourseCount()) {
                            userClassHouse = orderDetail.getResidueCourseCount();
                            diffClassHosue = diffClassHosue - orderDetail.getResidueCourseCount();
                        } else {
                            userClassHouse = diffClassHosue;
                            diffClassHosue = 0;
                        }


                        RecordCost recordCost = new RecordCost();
                        recordCost.setId(idWorker.nextId());
                        recordCost.setRecordCourseId(recordCourse.getId());
                        recordCost.setOrderDetailId(orderDetail.getId());

                        /**
                         * 本次使用金额 = 扣课时金额 + 服务费 + 材料费
                         */
                        BigDecimal buckleClassMoneyOther = new BigDecimal("0");

                        //判断是否第一次扣课时,第一次扣课时，把服务费和材料费一起扣了
                        /*if(orderDetail.getUseCourseCount() == 0){
                            recordCost.setServePrice(coursePricing.getServePrice());
                            recordCost.setMaterialsPrice(coursePricing.getMaterialsPrice());
                            buckleClassMoneyAll = buckleClassMoneyAll.add(coursePricing.getServePrice()).add(coursePricing.getMaterialsPrice());
                        }else {
                            recordCost.setServePrice(new BigDecimal(0));
                            recordCost.setMaterialsPrice(new BigDecimal(0));
                        }*/

                        //BigDecimal stuDeductHour =  new BigDecimal(grade.getStuDeductHour());
                        //本次扣多少个课时
                        BigDecimal stuDeductHour = new BigDecimal(userClassHouse);
                        //学生此次扣课时使用金额
                        BigDecimal buckleClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3), BigDecimal.ROUND_HALF_UP));

                        buckleClassMoneyOther = buckleClassMoneyOther.add(buckleClassMoney);

                        /**
                         * compareTo 反回1 表示大于，0等于，-1小于
                         * 如果此次扣除金额大于剩余金额，则改为使用剩余金额
                         */
                        if (buckleClassMoneyOther.compareTo(orderDetail.getResiduePrice()) > 0) {
                            buckleClassMoney = orderDetail.getResiduePrice();
                            buckleClassMoneyOther = buckleClassMoney;
                        } else if (orderDetail.getResidueCourseCount().compareTo(buckleClassHouse) == 0) {
                            buckleClassMoney = orderDetail.getResiduePrice();
                            buckleClassMoneyOther = buckleClassMoney;
                        }
                        buckleClassHourAll = buckleClassHourAll.add(stuDeductHour);
                        buckleClassMoneyAll = buckleClassMoneyAll.add(buckleClassMoney);


                        //老师课时获得金额
                        BigDecimal courseInMoney = staff.getCourseInMoney();
                        BigDecimal courseInCount = new BigDecimal(staff.getCourseInCount());
                        if (courseInCount.compareTo(new BigDecimal(0)) <= 0) {
                            throw new CommonException(ResultCode.TeacherHouseError);
                        }
                        //BigDecimal teaGainHour = new BigDecimal(grade.getTeaGainHour());//班级上一节课，老师得课时
                        //BigDecimal teaGainMoney = teaGainHour.divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                        recordCost.setBuckleClassHouse(buckleClassHouse);
                        recordCost.setBuckleClassMoney(buckleClassMoney);//本次扣课时金额

                        recordCost.setTeacherGetHouse(userClassHouse);//老师得课时
                        //BigDecimal teaGainMoney = new BigDecimal(userClassHouse).divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);
                        BigDecimal teaGainMoney = new BigDecimal(0);
                        //镇级
                        if (recordCourse.getSchoolId() != null && recordCourse.getSchoolId().equals(1697088501396127745L)) {
                            teaGainMoney = new BigDecimal(17);
                        } else {
                            teaGainMoney = new BigDecimal(20);
                        }

                        recordCost.setTeacherGetMoney(teaGainMoney);//老师得金额

                        teaGainHourAll = teaGainHourAll.add(new BigDecimal(userClassHouse));
                        teaGainMoneyAll = teaGainMoneyAll.add(teaGainMoney);

                        //全新订单里的使用课时，剩余课时，剩余金额，使用金额
                        //UpdateWrapper<OrderDetail> orderDetailUpdateWrapper = new UpdateWrapper<>();
                        //OrderDetail orderDetail = iOrderDetailService.getById(orderDetail.get());
                        /**
                         使用课时：use_course_count
                         上课累计使用金额：use_price
                         剩余课时：residue_course_count
                         剩余金额：residue_price
                         */
                        //扣课时
                        //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                        Integer useCourseCountForOrder = orderDetail.getUseCourseCount() + userClassHouse;
                        Integer residueCourseCountForUse = orderDetail.getResidueCourseCount() - userClassHouse;

                        orderDetail.setResidueCourseCount(residueCourseCountForUse);//剩余课时
                        orderDetail.setUseCourseCount(useCourseCountForOrder);//使用课时

                        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额
                        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额

                        orderDetailMapper.updateById(orderDetail);

                        //UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
                        //recordCostUpdateWrapper.eq("id",recordCost.getId());
                        iRecordCostService.saveOrUpdate(recordCost);

                        //更新分班里使用的课时
                        QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                        studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                        studentGradeQueryWrapper.eq("status", 1);
                        studentGradeQueryWrapper.eq("deleted", 0);
                        studentGradeQueryWrapper.eq("reading_status", 1);
                        studentGradeQueryWrapper.last("limit 1");
                        StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                        if (studentGrade == null) {
                            studentGradeQueryWrapper = new QueryWrapper<>();

                            studentGradeQueryWrapper.eq("school_id", courseSchedulingDetailInfo.getSchoolId());
                            studentGradeQueryWrapper.eq("student_id", orderDetail.getStudentId());
                            studentGradeQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
                            studentGradeQueryWrapper.ne("status", 2);
                            studentGradeQueryWrapper.eq("deleted", 0);
                            studentGradeQueryWrapper.eq("reading_status", 1);
                            studentGradeQueryWrapper.orderByDesc("created_at");
                            studentGradeQueryWrapper.last("limit 1");
                            studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                        }

                        if (studentGrade != null) {
                            Integer useCourseCount = studentGrade.getUseCourseCount() + userClassHouse;//使用课时
                            studentGrade.setUseCourseCount(useCourseCount);
                            iStudentGradeService.updateById(studentGrade);
                        }

                    }
                    recordCourse.setBuckleClassHouse(Integer.parseInt(buckleClassHourAll.toString()));
                    recordCourse.setBuckleClassMoney(buckleClassMoneyAll);
                    recordCourse.setTeacherGetHouse(Integer.parseInt(teaGainHourAll.toString()));
                    recordCourse.setTeacherGetMoney(teaGainMoneyAll);

                    UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
                    recordCourseUpdateWrapper.eq("scheduling_detail_id", courseSchedulingDetail.getId());
                    recordCourseUpdateWrapper.eq("student_id", recordCourse.getStudentId());
                    this.saveOrUpdate(recordCourse, recordCourseUpdateWrapper);
                    recordCourseList.add(recordCourse);

                    //临时记上课记录
                    RecordCourseTemp recordCourseTemp = new RecordCourseTemp();
                    recordCourseTemp.setId(recordCourseId);
                    recordCourseTemp.setGradeId(courseSchedulingDetailInfo.getGradeId());
                    recordCourseTemp.setStudentId(recordCourse.getStudentId());
                    recordCourseTemp.setStatus(recordCourse.getStatus());
                    recordCourseTemp.setSchedulingDetailId(courseSchedulingDetailInfo.getId());
                    recordCourseTemp.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
                    recordCourseTemp.setTimeStart(courseSchedulingDetailInfo.getTimeStart());
                    recordCourseTemp.setTimeEnd(courseSchedulingDetailInfo.getTimeEnd());
                    recordCourseTempList.add(recordCourseTemp);

                    //1排课班级里的学员，2临时学员，3补课学员
                    if (recordCourse.getType().equals(2) || recordCourse.getType().equals(3)) {
                        StudentGradeTemporary studentGradeTemporary = new StudentGradeTemporary();
                        studentGradeTemporary.setGradeId(courseSchedulingDetailInfo.getGradeId());
                        studentGradeTemporary.setStudentId(recordCourse.getStudentId());
                        studentGradeTemporary.setSchedulingDetailId(recordCourse.getSchedulingDetailId());
                        studentGradeTemporary.setType(recordCourse.getType());
                        iStudentGradeTemporaryService.save(studentGradeTemporary);
                    }

                    Integer residueCourseCountNew = orderDetailMapper.getResidueCourseCountForSubjects(courseSchedulingDetailInfo.getSchoolId(), recordCourse.getStudentId(), courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType(),yearClassId);
                    //System.out.println("residueCourseCountNew:"+residueCourseCountNew);
                    StringBuilder first = new StringBuilder();
                    first.append("(").append(organization.getName()).append(")").append("新增上课记录，请查看");
                    String keyword1 = student.getName();
                    StringBuilder keyword2 = new StringBuilder();
                    keyword2.append(courseSchedulingDetailInfo.getSchoolDate()).append(" ").append(courseSchedulingDetailInfo.getTimeStart()).append("-").append(courseSchedulingDetailInfo.getTimeEnd());
                    StringBuilder remark = new StringBuilder();
                    //remark.append("考勤状态为“上课”，").append("消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时");

                    StringBuilder keyword3 = new StringBuilder();
                    keyword3.append("考勤状态为“上课”，消耗").append(buckleClassHouse).append("课时");
                    StringBuilder keyword4 = new StringBuilder();
                    keyword4.append(residueCourseCountNew).append("课时").append(",如有疑问请及时与老师联系");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(recordCourse.getStudentId());

                    iWecharsBindService.wxPushUseCourseHouse(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), keyword4.toString(), remark.toString(), courseSchedulingDetailInfo.getId() + "" + student.getId());

                } else if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE)) {
                    //请假数据，暂时不添加到记上课
                    //recordCourseList.add(recordCourse);
                    UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
                    recordCourseUpdateWrapper.eq("scheduling_detail_id", courseSchedulingDetail.getId());
                    recordCourseUpdateWrapper.eq("student_id", recordCourse.getStudentId());
                    this.saveOrUpdate(recordCourse, recordCourseUpdateWrapper);

                    //临时记上课记录
                    RecordCourseTemp recordCourseTemp = new RecordCourseTemp();
                    recordCourseTemp.setId(recordCourseId);

                    recordCourseTemp.setGradeId(courseSchedulingDetailInfo.getGradeId());
                    recordCourseTemp.setStudentId(recordCourse.getStudentId());
                    recordCourseTemp.setStatus(recordCourse.getStatus());
                    recordCourseTemp.setSchedulingDetailId(courseSchedulingDetailInfo.getId());
                    recordCourseTemp.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
                    recordCourseTemp.setTimeStart(courseSchedulingDetailInfo.getTimeStart());
                    recordCourseTemp.setTimeEnd(courseSchedulingDetailInfo.getTimeEnd());
                    recordCourseTempList.add(recordCourseTemp);
                }
            }
        }
        if (recordCourseList.size() > 0) {
            //已上上面做添加操作，暂时注释掉
            //this.saveBatch(recordCourseList,recordCourseList.size());
            //设置已记上课
            courseSchedulingDetailInfo.setStatus(StatusSchedulingEnum.ON);
            iCourseSchedulingDetailService.updateById(courseSchedulingDetailInfo);
        }
        if (recordCourseTempList.size() > 0) {
            iRecordCourseTempService.saveBatch(recordCourseTempList);
        }
        return true;
    }


    /**
     * @param schoolId
     * @param studentId
     * @param subjectsId
     * @return
     */
    public boolean deductClassHours(Long schoolId, Long studentId, Long subjectsId) {
        return true;
    }

    /**
     * @param courseSchedulingDetailId
     * @param studentId
     * @param statusRecordEnum
     * @param type                     1排课班级里的学员，2临时学员，3补课学员
     * @return
     */
    public boolean addForSchedulingId(Long courseSchedulingDetailId, Long studentId, StatusRecordEnum statusRecordEnum, Integer type) {
        Integer stuDeductHour = 3;
        Integer teaGainHour = 3;

        CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(courseSchedulingDetailId);
        RecordCourse recordCourse = new RecordCourse();
        recordCourse.setStudentId(studentId);
        recordCourse.setStatus(statusRecordEnum);
        recordCourse.setType(type);
        recordCourse.setReachType(ReachTypeEnum.NORMAL);


        //老师
        recordCourse.setTeacherId(courseSchedulingDetailInfo.getTeacherId());
        Staff staff = iStaffService.getById(courseSchedulingDetailInfo.getTeacherId());
        if (staff == null) {
            //throw new CommonException(ResultCode.TeacerNo);
        }
        if (staff.getIsTeacher() != 1) {
            //throw new CommonException(ResultCode.NotATeacher);
        }
        recordCourse.setTeacherName(staff.getName());

        recordCourse.setSchedulingDetailId(courseSchedulingDetailInfo.getId());
        //校区
        recordCourse.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
        Organization organization = iOrganizationService.getById(courseSchedulingDetailInfo.getSchoolId());
        if (organization != null) {
            recordCourse.setSchoolName(organization.getName());
        }
        //班级
        recordCourse.setGradeId(courseSchedulingDetailInfo.getGradeId());
        /*
        Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());

       if(grade==null){
            //throw new CommonException(ResultCode.CourseSchedulingClassNo);
            //recordCourse.setTeacherGetHouse(grade.getStuDeductHour());//等确定
        }
        Course course = iCourseService.getById(grade.getCourseId());
        if(course==null){
            //throw new CommonException(ResultCode.COURSE_NOT);
        }*/

        Long courseId = null;
        String courseName = "";
        if (courseSchedulingDetailInfo.getGradeId() != null) {
            Course course = iCourseService.getById(courseSchedulingDetailInfo.getGradeId());
            if (course != null) {
                courseId = course.getId();
                courseName = course.getName();
            }
        }


        //年份与月份
        Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());

        recordCourse.setYearAndQuarter(yearAndQuarter);
        recordCourse.setGradeName(courseSchedulingDetailInfo.getGradeName());
        recordCourse.setCourseId(courseId);
        recordCourse.setCourseName(courseName);
        recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
        recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
        recordCourse.setTimeStart(courseSchedulingDetailInfo.getTimeStart());
        recordCourse.setTimeEnd(courseSchedulingDetailInfo.getTimeEnd());

        //教室
        recordCourse.setClassRoomId(courseSchedulingDetailInfo.getClassRoomId());
        ClassRoom classRoom = iClassRoomService.getById(courseSchedulingDetailInfo.getClassRoomId());
        if (classRoom != null) {
            recordCourse.setClassRoomName(classRoom.getName());
        }
        //科目
        recordCourse.setSubjectsId(courseSchedulingDetailInfo.getSubjectsId());
        Subjects subjects = iSubjectsService.getById(courseSchedulingDetailInfo.getSubjectsId());
        if (subjects != null) {
            recordCourse.setSubjectsName(subjects.getName());
        }
        recordCourse.setYearPart(courseSchedulingDetailInfo.getYearPart());
        recordCourse.setQuarter(courseSchedulingDetailInfo.getQuarter());
        recordCourse.setBuckleClassHouse(stuDeductHour);
        recordCourse.setTeacherGetHouse(teaGainHour);

        UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
        recordCourseUpdateWrapper.eq("scheduling_detail_id", courseSchedulingDetailId);
        recordCourseUpdateWrapper.eq("student_id", studentId);
        this.saveOrUpdate(recordCourse, recordCourseUpdateWrapper);
        return true;
    }

    /**
     * 自动扣课时
     *
     * @return
     */
    public boolean autoRecord() {
        LocalDateTime localDateTime = LocalDateTime.now().withNano(0);
        LocalDate nowLocalDate = LocalDate.now();
        return this.autoRecordAction(nowLocalDate, localDateTime);
    }

    /**
     * 消课bug，暂时添加数据，后面删除
     */
    @Override
    public void autoRecordAction2() {
        Integer stuDeductHour = 3;
        Integer teaGainHour = 3;
        try {
            Quarter quarterNow = iQuarterService.getNowQuarter();

            //获取 3补课,4调课，5消课,6缺课补课
            QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
            repairCourseQueryWrapper.eq("year_part", 2023);
            repairCourseQueryWrapper.eq("quarter", 4);
            repairCourseQueryWrapper.in("course_type", 5);
            repairCourseQueryWrapper.in("id", 1747938273906393088L, 1747938207191793664L, 1747937719587176448L, 1747937633390034944L, 1747937551471083520L, 1747937473851293696L, 1747937398500622336L, 1747936021040857088L, 1747935614621188096L, 1747934090549526528L, 1747933484384518144L, 1747932305772511232L, 1747613034676748288L, 1747612859153514496L, 1747612634598866944L);
            //repairCourseQueryWrapper.eq("school_date","2024-01-17");

            repairCourseQueryWrapper.eq("status", 0);
            repairCourseQueryWrapper.groupBy("student_id");
            //repairCourseQueryWrapper.eq("student_id",1600748532065632256L);
            //repairCourseQueryWrapper.eq("deleted",0);
            List<RepairCourse> repairCourseList = repairCourseMapper.selectList(repairCourseQueryWrapper);
            //System.out.println("repairCourseList:" + repairCourseList.size());
            for (RepairCourse repairCourse : repairCourseList) {
                /**智能课，刷题班暂时不扣课时*/
                if (!repairCourse.getLessonType().equals(1)) {
                    continue;
                }
                if (repairCourse.getCourseType().equals(4) || repairCourse.getCourseType().equals(5) || repairCourse.getCourseType().equals(6)) {
                    QueryWrapper<RecordCourse> recordCourseQueryWrapperDeduct = new QueryWrapper<>();
                    recordCourseQueryWrapperDeduct.eq("scheduling_detail_id", repairCourse.getId());
                    recordCourseQueryWrapperDeduct.eq("student_id", repairCourse.getStudentId());
                    recordCourseQueryWrapperDeduct.eq("is_deduct_house", 0);
                    recordCourseQueryWrapperDeduct.last("limit 1");
                    RecordCourse recordCourse = recordCourseMapper.selectOne(recordCourseQueryWrapperDeduct);
                    //Grade grade = iGradeService.getById(repairCourse.getGradeId());
                    StatusRecordEnum statusRecordEnum = StatusRecordEnum.REACH;
                    //到课
                    if (recordCourse != null) {
                    } else {
                        //没有到课
                        if (repairCourse.getIsSignIn().equals(0)) {
                            //请假补课,缺课补课的，未到课不做上课记录，不扣课时
                            if (repairCourse.getCourseType().equals(3) || repairCourse.getCourseType().equals(6)) {
                                continue;
                            }
                            statusRecordEnum = StatusRecordEnum.LEAVE;
                            RecordCourse recordCourseNo = this.addLeaveDataForRepair(repairCourse.getId(), repairCourse.getStudentId(), stuDeductHour, statusRecordEnum, 1, repairCourse.getCourseType(), repairCourse.getIsSignIn());
                            if (recordCourseNo != null) {
                                Boolean rs = this.recordActionRepair(recordCourseNo);
                                if (rs) {
                                    repairCourse.setStatus(1);
                                    repairCourseMapper.updateById(repairCourse);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("e:" + e.getMessage());
        }
    }


    @Override
    public boolean autoRecordAction(LocalDate nowLocalDate, LocalDateTime localDateTime) {
        Integer stuDeductHour = 3;
        Integer teaGainHour = 3;
        try {
            Quarter quarterNow = iQuarterService.getNowQuarter();
            if (quarterNow == null) {
                return false;
            }

            QueryWrapper<CourseSchedulingDetail> courseSchedulingDetailQueryWrapper = new QueryWrapper<>();
            courseSchedulingDetailQueryWrapper.eq("school_date", nowLocalDate);
            courseSchedulingDetailQueryWrapper.le("end_date_time", localDateTime);
            courseSchedulingDetailQueryWrapper.eq("deleted", 0);
            courseSchedulingDetailQueryWrapper.eq("status", 0);
            courseSchedulingDetailQueryWrapper.eq("is_lock", 0);
            courseSchedulingDetailQueryWrapper.eq("year_part", quarterNow.getYearPart());
            courseSchedulingDetailQueryWrapper.eq("quarter", quarterNow.getNum());
            courseSchedulingDetailQueryWrapper.eq("grade_status", 1);//班级状态为正常的

            //获取排课信息
            List<CourseSchedulingDetail> courseSchedulingDetailList = iCourseSchedulingDetailService.getCourseSchedulingDetailList(courseSchedulingDetailQueryWrapper);

            //锁住数据
            if (courseSchedulingDetailList.size() > 0) {
                for (CourseSchedulingDetail courseSchedulingDetail : courseSchedulingDetailList) {
                    //锁数据
                    courseSchedulingDetail.setIsLock(1);
                    iCourseSchedulingDetailService.updateById(courseSchedulingDetail);
                }
            }

            //先处理未刷脸打卡的学生
            for (CourseSchedulingDetail courseSchedulingDetail : courseSchedulingDetailList) {
                Integer courseType = 1;
                if (courseSchedulingDetail.getType() != null) {
                    courseType = courseSchedulingDetail.getType().equals(1) ? 1 : 4;//4为调课
                }
                //班级里未刷脸打卡的学生
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.eq("grade_id", courseSchedulingDetail.getGradeId());
                studentGradeQueryWrapper.eq("deleted", 0);
                studentGradeQueryWrapper.ne("status", 2);
                studentGradeQueryWrapper.eq("reading_status", 1);
                studentGradeQueryWrapper.notInSql("student_id", "select student_id from student_sign_in_temp where scheduling_detail_id =" + courseSchedulingDetail.getId() + " ");
                studentGradeQueryWrapper.notInSql("student_id", "select student_id from repair_course where deleted = 0 and out_scheduling_detail_id =" + courseSchedulingDetail.getId() + " and course_type = 4");//排除调课调出的
                studentGradeQueryWrapper.groupBy("student_id");
                List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
                for (StudentGrade studentGrade : studentGradeList) {
                    QueryWrapper<RecordCourse> recordCourseQueryWrapperDeduct = new QueryWrapper<>();
                    recordCourseQueryWrapperDeduct.eq("scheduling_detail_id", courseSchedulingDetail.getId());
                    recordCourseQueryWrapperDeduct.eq("student_id", studentGrade.getStudentId());
                    recordCourseQueryWrapperDeduct.eq("year_class_id", studentGrade.getYearClassId());
                    recordCourseQueryWrapperDeduct.eq("is_deduct_house", 1);
                    Long count = recordCourseMapper.selectCount(recordCourseQueryWrapperDeduct);
                    //System.out.println("count："+count);
                    if (count.equals(0L)) {
                        //Grade grade = iGradeService.getById(studentGrade.getGradeId());
                        //先添加到上课记录

                        StatusRecordEnum statusRecordEnum = StatusRecordEnum.LEAVE;
                        //精品课才有旷课
                        if(studentGrade.getLessonType().equals(1)){
                            /** 不请假不来标为旷课*/
                            QueryWrapper<StudentLeaveApply> studentLeaveApplyQueryWrapper = new QueryWrapper<>();
                            studentLeaveApplyQueryWrapper
                                    .eq("student_id",studentGrade.getStudentId())
                                    .in("status",0,1);//未审核的也不算为旷课
                            studentLeaveApplyQueryWrapper.and(i->i.eq("start_date_time",courseSchedulingDetail.getStartDateTime()).eq("end_date_time",courseSchedulingDetail.getEndDateTime()).or(j->j.eq("scheduling_detail_id",courseSchedulingDetail.getId())));
                            Long leaveApplyCount = studentLeaveApplyService.count(studentLeaveApplyQueryWrapper);

                            if (leaveApplyCount.equals(0L) ) {
                                statusRecordEnum = StatusRecordEnum.Truancy;
                            }
                        }
                        RecordCourse recordCourse = null;
                        if (courseSchedulingDetail.getLessonType().equals(2) || courseSchedulingDetail.getLessonType().equals(3)){
                            //是否有未通关（已通关）
                            Integer notPassCount = 0;
                            try {
                                //notPassCount = recordCourseMapper.getNotPassCount(courseSchedulingDetail.getYearPart(),courseSchedulingDetail.getQuarter(),studentGrade.getStudentId(),nowLocalDate.toString(),courseSchedulingDetail.getStartDateTime().toString(),courseSchedulingDetail.getSubjectsId(),courseSchedulingDetail.getLessonType(),maxTaskLesson);

                                if(courseSchedulingDetail.getSubjectsId().equals(1L)){
                                    //英语
                                    //notPassCount = recordCourseMapper.getNotPassCount(courseSchedulingDetail.getYearPart(),courseSchedulingDetail.getQuarter(),studentGrade.getStudentId(),nowLocalDate.toString(),courseSchedulingDetail.getStartDateTime().toString(),courseSchedulingDetail.getSubjectsId(),courseSchedulingDetail.getLessonType(),30);
                                }else {Integer maxTaskLesson = this.getMaxTaskLesson(courseSchedulingDetail.getYearPart(),courseSchedulingDetail.getQuarter(),courseSchedulingDetail.getSubjectsId().toString(),1676874588501311488L,1);
                                    //获取出精品课所在班级，年级和班型使用
                                    StudentGrade studentGradeBoutique = iStudentGradeService.getLastOne(courseSchedulingDetail.getYearPart(),courseSchedulingDetail.getQuarter(),courseSchedulingDetail.getSubjectsId(),studentGrade.getStudentId(),1);
                                    if (!Objects.isNull(studentGradeBoutique)){
                                        //数学和物理
                                        //notPassCount = recordCourseMapper.getNotPassCountMath(courseSchedulingDetail.getYearPart(),courseSchedulingDetail.getQuarter(),courseSchedulingDetail.getSubjectsId(),studentGrade.getStudentId(),studentGradeBoutique.getYearClassId(),studentGradeBoutique.getClassTypeIdNew(),localDateTime.toString(),maxTaskLesson);
                                    }
                                }
                            }catch (Exception e){}
                            //有未通关的课次才添加（已通关）
                            if (notPassCount>0){
                                recordCourse = this.addLeaveData(courseSchedulingDetail.getId(), studentGrade.getStudentId(), stuDeductHour, statusRecordEnum, 1, courseType, quarterNow,studentGrade.getYearClassId());
                            }
                        }else {
                            recordCourse = this.addLeaveData(courseSchedulingDetail.getId(), studentGrade.getStudentId(), stuDeductHour, statusRecordEnum, 1, courseType, quarterNow,studentGrade.getYearClassId());
                        }
                        /**智能课，刷题班暂时不扣课时*/
                        if (!courseSchedulingDetail.getLessonType().equals(1)) {
                            continue;
                        }
                        if (recordCourse != null) {
                            //扣课时
                            Boolean rs = this.recordAction(recordCourse);
                        }
                    }
                }
                //courseSchedulingDetail.setStatus(StatusSchedulingEnum.ON);
                //解锁数据
                //courseSchedulingDetail.setIsLock(0);
                //iCourseSchedulingDetailService.updateById(courseSchedulingDetail);
            }

            for (CourseSchedulingDetail courseSchedulingDetail : courseSchedulingDetailList) {
                /*if (courseSchedulingDetail.getId().equals(1810842788556701696L)) {
                    System.out.println("------");
                }*/
                Integer courseType = 1;
                if (courseSchedulingDetail.getType() != null) {
                    courseType = courseSchedulingDetail.getType().equals(1) ? 1 : 4;//4为调课
                }
                //System.out.println("=============:"+courseSchedulingDetail.getCourseName());
                //已刷脸打卡的学生
                QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
                recordCourseQueryWrapper.eq("lesson_type", 1);/**智能课，刷题班暂时不扣课时*/
                recordCourseQueryWrapper.eq("scheduling_detail_id", courseSchedulingDetail.getId());
                recordCourseQueryWrapper.notInSql("student_id", "select student_id from repair_course where deleted = 0 and out_scheduling_detail_id =" + courseSchedulingDetail.getId() + " and course_type = 4");//排除调课调出的

                List<RecordCourse> recordCourseList = recordCourseMapper.selectList(recordCourseQueryWrapper);
                for (RecordCourse recordCourse : recordCourseList) {
                    //不等于已扣的
                    if (!recordCourse.getIsDeductHouse().equals(1)) {
                        Boolean rs = this.recordAction(recordCourse);
                        if (!rs) {
                            UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
                            recordCourseUpdateWrapper.eq("id", recordCourse.getId());
                            recordCourseUpdateWrapper.set("is_deduct_house", 2);//扣课时异常
                            recordCourseMapper.update(null, recordCourseUpdateWrapper);
                        }
                    }
                }

                courseSchedulingDetail.setStatus(StatusSchedulingEnum.ON);
                //解锁数据
                courseSchedulingDetail.setIsLock(0);
                iCourseSchedulingDetailService.updateById(courseSchedulingDetail);
            }

            //获取 3补课,4调课，5消课,6缺课补课
            QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
            repairCourseQueryWrapper.eq("year_part", quarterNow.getYearPart());
            repairCourseQueryWrapper.eq("quarter", quarterNow.getNum());

            repairCourseQueryWrapper.in("course_type", 3, 4, 5, 6,9);
            repairCourseQueryWrapper.eq("school_date", nowLocalDate);
            repairCourseQueryWrapper.le("end_date_time", localDateTime);

            repairCourseQueryWrapper.eq("status", 0);
            //repairCourseQueryWrapper.eq("student_id",1600748532065632256L);
            //repairCourseQueryWrapper.eq("deleted",0);
            List<RepairCourse> repairCourseList = repairCourseMapper.selectList(repairCourseQueryWrapper);
            for (RepairCourse repairCourse : repairCourseList) {
                try {
                    /**智能课，刷题班暂时不扣课时*/
                    if (!repairCourse.getLessonType().equals(1)) {
                        continue;
                    }


                    Long readingCount = iStudentGradeService.getStudentReadingCount(repairCourse.getYearPart(), repairCourse.getQuarter(), repairCourse.getSchoolId(), repairCourse.getSubjectsId(), repairCourse.getStudentId(), repairCourse.getLessonType());
                    //没有在读的跳过
                    if (readingCount.equals(0L)) {
                        continue;
                    }

                    if (repairCourse.getCourseType().equals(4) || repairCourse.getCourseType().equals(5) || repairCourse.getCourseType().equals(6) || repairCourse.getCourseType().equals(9)) {
                        QueryWrapper<RecordCourse> recordCourseQueryWrapperDeduct = new QueryWrapper<>();
                        recordCourseQueryWrapperDeduct.eq("scheduling_detail_id", repairCourse.getId());
                        recordCourseQueryWrapperDeduct.eq("student_id", repairCourse.getStudentId());
                        recordCourseQueryWrapperDeduct.eq("is_deduct_house", 0);
                        recordCourseQueryWrapperDeduct.last("limit 1");
                        RecordCourse recordCourse = recordCourseMapper.selectOne(recordCourseQueryWrapperDeduct);
                        //Grade grade = iGradeService.getById(repairCourse.getGradeId());
                        StatusRecordEnum statusRecordEnum = StatusRecordEnum.REACH;
                        //到课
                        if (recordCourse != null) {
                            Boolean rs = this.recordActionRepair(recordCourse);
                            if (rs) {
                                repairCourse.setStatus(1);
                                repairCourseMapper.updateById(repairCourse);
                                if (repairCourse.getCourseType().equals(6)) {
                                    iLackCourseLogService.updateIsRepair(repairCourse.getRecordCourseId());//缺课记录更新为已补课
                                }
                            }
                        } else {
                            //没有到课
                            if (repairCourse.getIsSignIn().equals(0)) {
                                //请假补课,缺课补课的，未到课不做上课记录，不扣课时
                                if (repairCourse.getCourseType().equals(3) || repairCourse.getCourseType().equals(6)|| repairCourse.getCourseType().equals(9)) {
                                    continue;
                                }
                                statusRecordEnum = StatusRecordEnum.LEAVE;
                                RecordCourse recordCourseNo = this.addLeaveDataForRepair(repairCourse.getId(), repairCourse.getStudentId(), stuDeductHour, statusRecordEnum, 1, repairCourse.getCourseType(), repairCourse.getIsSignIn());
                                if (recordCourseNo != null) {
                                    Boolean rs = this.recordActionRepair(recordCourseNo);
                                    if (rs) {
                                        repairCourse.setStatus(1);
                                        repairCourseMapper.updateById(repairCourse);
                                        if (repairCourse.getCourseType().equals(6)) {
                                            iLackCourseLogService.updateIsRepair(repairCourse.getRecordCourseId());//缺课记录更新为已补课
                                        }
                                    }
                                }
                            }
                        }
                    } else if (repairCourse.getCourseType().equals(3)) {
                        //System.out.println("0001");
                        //补课到课
                        if (repairCourse.getIsSignIn().equals(1)) {
                            //System.out.println("0002");
                            this.repairBuckleMoney(repairCourse.getId());
                        }
                    }
                } catch (Exception e) {
                }
            }
            //补扣没有扣的课时
            this.pathchMoney();
        } catch (Exception e) {
            System.out.println("e:" + e.getMessage());
            this.updateLock(localDateTime, 0, 0);
        }
        return true;
    }


    /**
     * @param localDateTime
     * @param status
     * @param isLock:0改为锁住，1改为取消锁住
     */
    private void updateLock(LocalDateTime localDateTime, Integer status, Integer isLock) {

        Integer oldIsLocck = isLock == 1 ? 0 : 1;

        UpdateWrapper<CourseSchedulingDetail> courseSchedulingDetailUpdateWrapper = new UpdateWrapper<>();
        LocalDate nowLocalDate = LocalDate.now();
        courseSchedulingDetailUpdateWrapper.eq("school_date", nowLocalDate);
        courseSchedulingDetailUpdateWrapper.le("end_date_time", localDateTime);
        courseSchedulingDetailUpdateWrapper.eq("deleted", 0);
        courseSchedulingDetailUpdateWrapper.eq("status", 0);
        courseSchedulingDetailUpdateWrapper.eq("is_lock", oldIsLocck);
        courseSchedulingDetailUpdateWrapper.set("is_lock", isLock);
        iCourseSchedulingDetailService.update(null, courseSchedulingDetailUpdateWrapper);
    }

    /**
     * 扣课时
     *
     * @param recordCourseParam
     * @return
     */
    @Transactional
    public boolean recordAction(RecordCourse recordCourseParam) {

        try {
            RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseParam.getId());
            if (recordCourse.getIsDeductHouse().equals(1)) {
                return true;
            }


            Long studentId = recordCourse.getStudentId();
            String studentName = recordCourse.getStudentName();
            Integer courseType = recordCourse.getCourseType();
            Long schedulingDetailId = recordCourse.getSchedulingDetailId();

            //QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
            //queryWrapper.eq("scheduling_detail_id",schedulingDetailId);
            //queryWrapper.eq("student_id",studentId);
            //queryWrapper.eq("status",1);
            //queryWrapper.in("is_deduct_house",0,3);//不等于未扣课时的
            //Long count = recordCourseMapper.selectCount(queryWrapper);
            //不等于0

            String courseTypeName = "";
            if (courseType.equals(4)) {
                courseTypeName = "(调课)";
            } else if (courseType.equals(5)) {
                courseTypeName = "(消课)";
            }

            CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(schedulingDetailId);
            if (courseSchedulingDetailInfo == null) {
                return false;
            }
            Integer yearClassId = 0;
            Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());
            if (Objects.nonNull(grade)) {
                yearClassId = grade.getYearClassId().getKey();
            }
            /*if(grade==null){
                return false;
            }
            //Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                return false;
            }*/

            //扣多少个课时
            Integer buckleClassHouse = 3;//grade.getStuDeductHour();

            Integer teaGainHour = 3;

            Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());

            //使用本学期使用课时
            Long useCount = iStudentGradeService.getStudentUseCourseCount(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSchoolId(), courseSchedulingDetailInfo.getSubjectsId(), studentId, courseSchedulingDetailInfo.getLessonType(),recordCourse.getYearClassId());


            //状态不为消课的
            if (!courseType.equals(5) && courseSchedulingDetailInfo.getLessonType().equals(1)) {
                //请假，请假的不添加数据，直接返回
                Quarter quarter = iQuarterService.getQuarterForYearAndNum(recordCourse.getYearPart(),recordCourse.getQuarter());
                //0不继续扣，1继续扣
                if (quarter.getIsDeductHouse().equals(0)){
                    if (useCount >= 45) {
                        //大于45课时，请假的不添加记录
                        RecordCourse recordCourseLeave = this.getLeaveData(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId(),recordCourse.getYearClassId());
                        boolean rsBuckMoney = false;
                        if (recordCourseLeave != null) {
                            rsBuckMoney = this.greaterBuckleMoney(recordCourse, recordCourseLeave);
                        }

                        if (recordCourseLeave == null || rsBuckMoney == false) {
                            UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
                            recordCourseUpdateWrapper.set("is_deduct_house", 3);
                            recordCourseUpdateWrapper.set("is_deduct_money", 3);
                            recordCourseUpdateWrapper.set("remark", "已扣15课次，不需要扣课时");
                            recordCourseUpdateWrapper.eq("id", recordCourse.getId());
                            this.update(null, recordCourseUpdateWrapper);
                            rsBuckMoney = true;
                        }

                        return rsBuckMoney;
                    }
                }
            }

            //Student student = studentMapper.selectById(studentId);

            Staff staff = iStaffService.getById(courseSchedulingDetailInfo.getTeacherId());

            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(courseSchedulingDetailInfo.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType(),recordCourse.getYearClassId());

            if (residueCourseCount < buckleClassHouse) {
                //剩余课时为0时，判断是否有请假记录
                RecordCourse recordCourseLeave = this.getLeaveData(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId(),recordCourse.getYearClassId());
                boolean rsBuckMoney = false;
                if (recordCourseLeave != null) {
                    rsBuckMoney = this.greaterBuckleMoney(recordCourse, recordCourseLeave);
                    return rsBuckMoney;
                }

                if (recordCourseLeave == null || rsBuckMoney == false) {
                    RecordError recordError = new RecordError();
                    recordError.setRecordCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                    recordError.setStudentId(studentId);
                    recordError.setContent("此学生：" + recordCourse.getStudentName() + ",课程：" + courseSchedulingDetailInfo.getCourseName() + "剩余课时不足：" + buckleClassHouse);
                    iRecordErrorService.save(recordError);
                }
                //此学生该课程没有可用课时
                return rsBuckMoney;
            }

            //设置是否需要改为结课
            ReadingStatusEnum readingStatusEnum = ReadingStatusEnum.IN_READING;
            //请假未补数量
            Integer lackCount = 0;
            try {
                lackCount = recordCourseMapper.getLackCount(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), studentId, courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getLessonType());
            } catch (Exception e) {
            }
            if (residueCourseCount == buckleClassHouse && lackCount.equals(0)) {
                readingStatusEnum = ReadingStatusEnum.FINISH;
            }

            List<OrderDetail> orderDetailList = orderDetailMapper.orderDetailListForSubjects(courseSchedulingDetailInfo.getSchoolId(), studentId, courseSchedulingDetailInfo.getSubjectsId(), yearAndQuarter, courseSchedulingDetailInfo.getLessonType(),yearClassId);

            Integer diffClassHosue = buckleClassHouse;//还差多少课时

            Integer teaGainHourAll = 0;//老师得课时总课时
            BigDecimal teaGainMoneyAll = new BigDecimal(0);

            BigDecimal buckleClassMoneyAll = new BigDecimal(0);
            BigDecimal buckleClassHourAll = new BigDecimal(0);

            //老师课时获得金额
            BigDecimal courseInMoney = staff.getCourseInMoney();
            BigDecimal courseInCount = new BigDecimal(staff.getCourseInCount());
            if (courseInCount.compareTo(new BigDecimal(0)) <= 0) {
                return false;
            }

            iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourse.getId()));//先删除详情
            Long lastOrderDetailId = null;

            //获取使用的请假次数
            Integer useLeaveCount = 0;
            if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                useLeaveCount = recordCourseMapper.getUseLeaveCount(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getLessonType());
            }

            for (OrderDetail orderDetail : orderDetailList) {
                if (diffClassHosue == 0) {
                    continue;
                }

                CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
                if (coursePricing == null) {
                    //此学生数据异常
                    RecordError recordError = new RecordError();
                    recordError.setRecordCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setCourseId(courseSchedulingDetailInfo.getCourseId());
                    recordError.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
                    recordError.setStudentId(studentId);
                    recordError.setContent("此学生课程价格数据异常：" + orderDetail.getCoursePriceId());
                    iRecordErrorService.save(recordError);
                    continue;
                }

                Integer userClassHouse = 0;//本次使用课时
                //本次要扣的课时大于等于剩余课时
                if (diffClassHosue > orderDetail.getResidueCourseCount()) {
                    userClassHouse = orderDetail.getResidueCourseCount();
                    diffClassHosue = diffClassHosue - orderDetail.getResidueCourseCount();
                } else {
                    userClassHouse = diffClassHosue;
                    diffClassHosue = 0;
                }

                RecordCost recordCost = new RecordCost();
                recordCost.setId(idWorker.nextId());
                recordCost.setRecordCourseId(recordCourse.getId());
                recordCost.setOrderDetailId(orderDetail.getId());
                lastOrderDetailId = orderDetail.getId();

                /**
                 * 本次使用金额 = 扣课时金额 + 服务费 + 材料费
                 */
                BigDecimal buckleClassMoneyOther = new BigDecimal("0");

                //本次扣多少个课时
                BigDecimal stuDeductHour = new BigDecimal(userClassHouse);
                //学生此次扣课时使用金额
                BigDecimal buckleClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3), BigDecimal.ROUND_HALF_UP));

                buckleClassMoneyOther = buckleClassMoneyOther.add(buckleClassMoney);

                /**
                 * compareTo 反回1 表示大于，0等于，-1小于
                 * 如果此次扣除金额大于剩余金额，则改为使用剩余金额
                 */

                //缺课未补的金额
                BigDecimal lackMoney = recordCourseLackMapper.getAllBucklemoneyForOrderDetailId(orderDetail.getId());
                //BigDecimal lackMoney = BigDecimal.ZERO;
                BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                if (residuePrice.compareTo(BigDecimal.ZERO) < 0)
                    residuePrice = new BigDecimal(0);
                if (userClassHouse == orderDetail.getResidueCourseCount()) {
                    if(lackMoney.compareTo(BigDecimal.ZERO)>0){
                        if (residuePrice.subtract(lackMoney).compareTo(buckleClassMoney)>0){
                            buckleClassMoney = residuePrice.subtract(lackMoney);
                        }else {
                            if (residuePrice.compareTo(buckleClassMoney)<0){
                                buckleClassMoney = residuePrice;
                            }
                        }
                    }else {
                        //使用可是等于剩余课时
                        buckleClassMoney = residuePrice;
                    }
                    buckleClassMoneyOther = buckleClassMoney;
                } else if (buckleClassMoneyOther.compareTo(residuePrice) > 0) {
                    //本次使用金额大于剩余金额
                    buckleClassMoney = residuePrice;
                    buckleClassMoneyOther = buckleClassMoney;
                }

                buckleClassHourAll = buckleClassHourAll.add(stuDeductHour);
                buckleClassMoneyAll = buckleClassMoneyAll.add(buckleClassMoney);

                //BigDecimal teaGainHour = new BigDecimal(grade.getTeaGainHour());//班级上一节课，老师得课时
                //BigDecimal teaGainMoney = teaGainHour.divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                recordCost.setBuckleClassHouse(userClassHouse);

                Integer teacherGetClassHosue = (userClassHouse / 3) * teaGainHour;//教师得多少课时

                //BigDecimal teaGainMoney = new BigDecimal(teacherGetClassHosue).divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);
                BigDecimal teaGainMoney = new BigDecimal(0);
                //镇级
                if (recordCourse.getSchoolId() != null && recordCourse.getSchoolId().equals(1697088501396127745L)) {
                    teaGainMoney = new BigDecimal(17);
                } else {
                    teaGainMoney = new BigDecimal(20);
                }

                teaGainHourAll = teaGainHourAll + teacherGetClassHosue;
                teaGainMoneyAll = teaGainMoneyAll.add(teaGainMoney);

                //全新订单里的使用课时，剩余课时，剩余金额，使用金额
                /**
                 使用课时：use_course_count
                 上课累计使用金额：use_price
                 剩余课时：residue_course_count
                 剩余金额：residue_price
                 */
                //扣课时
                //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                Integer useCourseCountForOrder = orderDetail.getUseCourseCount() + userClassHouse;
                orderDetail.setUseCourseCount(useCourseCountForOrder);//累计使用课时

                Integer residueCourseCountForUse = orderDetail.getResidueCourseCount() - userClassHouse;
                orderDetail.setResidueCourseCount(residueCourseCountForUse);//剩余课时
                //到课或者旷课都扣课时与金额
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) || recordCourse.getStatus().equals(StatusRecordEnum.Truancy)) {
                    recordCost.setBuckleClassMoney(buckleClassMoney);//本次扣课时金额
                    recordCost.setTeacherGetHouse(userClassHouse);//老师得课时
                    recordCost.setTeacherGetMoney(teaGainMoney);//老师得金额

                    orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
                    orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额
                } else {
                    if (useLeaveCount > 2) {//因为是先添加了请假数据，因为这里是大于2
                        recordCost.setBuckleClassMoney(buckleClassMoney);//本次扣课时金额
                        recordCost.setTeacherGetHouse(userClassHouse);//老师得课时
                        recordCost.setTeacherGetMoney(teaGainMoney);//老师得金额

                        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
                        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额
                    }
                }

                orderDetailMapper.updateById(orderDetail);

                //UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
                //recordCostUpdateWrapper.eq("id",recordCost.getId());
                iRecordCostService.save(recordCost);

                //更新分班里使用的课时
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                studentGradeQueryWrapper.eq("status", 1);
                studentGradeQueryWrapper.eq("deleted", 0);
                studentGradeQueryWrapper.eq("reading_status", 1);
                studentGradeQueryWrapper.eq("lesson_type", courseSchedulingDetailInfo.getLessonType());
                //studentGradeQueryWrapper.eq("grade_id",courseSchedulingDetailInfo.getGradeId());
                studentGradeQueryWrapper.last("limit 1");
                StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                if (studentGrade == null) {
                    studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(courseSchedulingDetailInfo.getSchoolId(), orderDetail.getStudentId(), courseSchedulingDetailInfo.getSubjectsId(), courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getLessonType());
                }

                if (studentGrade != null) {
                    Integer useCourseCount = studentGrade.getUseCourseCount() + userClassHouse;//累计使用课时
                    studentGrade.setUseCourseCount(useCourseCount);
                    studentGrade.setReadingStatus(readingStatusEnum);
                    iStudentGradeService.updateById(studentGrade);
                    recordCourse.setStudentGradeId(studentGrade.getId());
                }
                if (readingStatusEnum.getKey().equals(5)) {
                    studentGradeQueryWrapper = new QueryWrapper<>();
                    studentGradeQueryWrapper.eq("school_id", courseSchedulingDetailInfo.getSchoolId());
                    studentGradeQueryWrapper.eq("student_id", orderDetail.getStudentId());
                    studentGradeQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
                    studentGradeQueryWrapper.eq("lesson_type", courseSchedulingDetailInfo.getLessonType());
                    studentGradeQueryWrapper.ne("status", 2);
                    studentGradeQueryWrapper.eq("deleted", 0);
                    studentGradeQueryWrapper.eq("reading_status", 1);
                    studentGradeQueryWrapper.orderByDesc("created_at");
                    List<StudentGrade> studentGradeList = iStudentGradeService.list(studentGradeQueryWrapper);
                    for (StudentGrade studentGradeUpdate : studentGradeList) {
                        studentGradeUpdate.setReadingStatus(readingStatusEnum);
                        iStudentGradeService.updateById(studentGradeUpdate);
                    }

                }
            }
            recordCourse.setBuckleClassHouse(Integer.parseInt(buckleClassHourAll.toString()));
            recordCourse.setOrderDetailId(lastOrderDetailId);
            recordCourse.setIsDeductHouse(1);
            recordCourse.setRemark("");
            //recordCourse.setLessonType(grade.getLessonType());
            recordCourse.setDeductType(1);//扣课时方式，0未知，1自动，2是手动

            //到课
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) || recordCourse.getStatus().equals(StatusRecordEnum.Truancy)) {
                recordCourse.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourse.setTeacherGetHouse(Integer.parseInt(teaGainHourAll.toString()));
                recordCourse.setTeacherGetMoney(teaGainMoneyAll);
                recordCourse.setIsDeductMoney(1);
            } else {
                if (useLeaveCount > 2) {
                    recordCourse.setBuckleClassMoney(buckleClassMoneyAll);
                    recordCourse.setTeacherGetHouse(Integer.parseInt(teaGainHourAll.toString()));
                    recordCourse.setTeacherGetMoney(teaGainMoneyAll);
                    recordCourse.setIsDeductMoney(1);
                    recordCourse.setUseLeaveNum(1);
                    recordCourse.setDeductType(4);
                } else {
                    recordCourse.setIsDeductMoney(0);
                }
            }

            if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE) || recordCourse.getStatus().equals(StatusRecordEnum.Truancy)) {
                recordCourse.setUseLeaveNum(1);
            } else {
                recordCourse.setUseLeaveNum(courseSchedulingDetailInfo.getUseLeaveNum());//设置是否是请假次数添加一次
            }


            //UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
            //recordCourseUpdateWrapper.eq("scheduling_detail_id",schedulingDetailId);
            //recordCourseUpdateWrapper.eq("student_id",recordCourse.getStudentId());
            this.updateById(recordCourse);

            if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE)) {
                //缺课的金额暂时保存
                RecordCourseLack recordCourseLack = new RecordCourseLack();
                recordCourseLack.setId(recordCourse.getId());
                recordCourseLack.setOrderDetailId(recordCourse.getOrderDetailId());
                recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
                recordCourseLack.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourseLack.setTeacherGetHouse(teaGainHourAll);
                recordCourseLack.setTeacherGetMoney(teaGainMoneyAll);
                iRecordCourseLackService.saveOrUpdate(recordCourseLack);
            }

            //到课，发送微信提醒
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("school_id", courseSchedulingDetailInfo.getSchoolId());
            studentGradeQueryWrapper.eq("student_id", studentId);
            studentGradeQueryWrapper.eq("subjects_id", courseSchedulingDetailInfo.getSubjectsId());
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("course_status", 1);//课时是否异常，异常的不推送家长,正常：1
            Long courseStatusCount = iStudentGradeService.count(studentGradeQueryWrapper);
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) || (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE) && useLeaveCount > 2)) {
                if (courseStatusCount > 0 && recordCourse.getLessonType().equals(1)) {
                    StringBuilder first = new StringBuilder();
                    first.append("(").append(courseSchedulingDetailInfo.getSchoolName()).append(")").append("新增上课记录，请查看");
                    String keyword1 = studentName;
                    StringBuilder keyword2 = new StringBuilder();
                    keyword2.append(courseSchedulingDetailInfo.getSchoolDate()).append(" ").append(courseSchedulingDetailInfo.getTimeStart()).append("-").append(courseSchedulingDetailInfo.getTimeEnd());
                    StringBuilder keyword3 = new StringBuilder();
                    Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;//剩余课时
                    StringBuilder keyword4 = new StringBuilder();

                    if ((recordCourse.getStatus().equals(StatusRecordEnum.LEAVE) || recordCourse.getStatus().equals(StatusRecordEnum.Truancy)) && useLeaveCount > 2) {
                        keyword3.append("考勤状态为“未到" + courseTypeName + "”，消耗").append(buckleClassHouse).append("课时");
                        keyword4.append(residueCourseCountNew).append("课时").append(",超过请假次数课时已扣");
                    } else {
                        keyword3.append("考勤状态为“上课" + courseTypeName + "”，消耗").append(buckleClassHouse).append("课时");
                        keyword4.append(residueCourseCountNew).append("课时").append(",如有疑问请及时与老师联系");
                    }

                    //StringBuilder remark = new StringBuilder();
                    //remark.append("考勤状态为“上课"+courseTypeName+"”，").append("消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(recordCourse.getStudentId());
                    iWecharsBindService.wxPushUseCourseHouse(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), keyword4.toString(), "", courseSchedulingDetailInfo.getId() + "" + studentId);
                }
            } else {
                if (courseStatusCount > 0 && recordCourse.getLessonType().equals(1)) {
                    StringBuilder first = new StringBuilder();
                    //小明家长，您好！小明xxxx年xx月xx日未能准时到校签到上课！
                    first.append("" + studentName + "家长，您好！" + studentName + "" + courseSchedulingDetailInfo.getSchoolDate() + "未能准时到校签到上课！");
                    String keyword1 = studentName;
                    StringBuilder keyword2 = new StringBuilder();

                    String gradeName = this.replaceGradeNameForStudentIdAndSubjectsId(courseSchedulingDetailInfo.getYearPart(),courseSchedulingDetailInfo.getQuarter(),studentId,courseSchedulingDetailInfo.getSubjectsId());
                    keyword2.append(gradeName);

                    StringBuilder keyword3 = new StringBuilder();
                    if (useLeaveCount <= 2 && useLeaveCount > 0) {
                        keyword3.append(courseSchedulingDetailInfo.getStartDateTime().toString().replace("T", " ") + " 已用" + useLeaveCount + "次请假次数");
                    } else {
                        //正常情况下不会执行到这里，正常情况使用大于两次是使用课时消耗上面的条件
                        keyword3.append(courseSchedulingDetailInfo.getStartDateTime().toString().replace("T", " "));
                    }

                    StringBuilder remark = new StringBuilder();
                    Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;
                    //remark.append("考勤状态为“缺课"+courseTypeName+"”，").append("课时已扣，消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时，请联系任课老师补课");
                    first.append("，考勤状态为“缺课" + courseTypeName + "”，").append("课时已扣，消耗“" + buckleClassHouse + "”课时，剩余“" + residueCourseCountNew + "”课时，请联系任课老师补课");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(recordCourse.getStudentId());
                    iWecharsBindService.wxPushMissAClass(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), remark.toString(), courseSchedulingDetailInfo.getId() + "" + studentId);
                }
            }

            /**
             * 如果到课,更新英语学习系统已上第一次课
             */
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)){
                if (recordCourse.getLessonNum() !=null){
                    if (recordCourse.getCourseType() == 1 && recordCourse.getLessonType().equals(1) && recordCourse.getLessonNum() == 1) {
                        StudentClassType studentClassType = new StudentClassType();
                        studentClassType.setYearPart(recordCourse.getYearPart());
                        studentClassType.setQuarterNum(recordCourse.getQuarter());
                        studentClassType.setStudentId(recordCourse.getStudentId());
                        studentClassType.setSubjectsId(recordCourse.getSubjectsId());
                        studentClassType.setIsUpFirst(1);
                        iMqPushService.syncIsUpFirst(studentClassType);
                    }
                }
            }

            return true;
        } catch (Exception e) {
            System.out.println("recordActionError:" + e.getMessage());
            return false;
        }
    }

    /**
     * 补课，调课，消课，缺课补课扣课时
     *
     * @param recordCourseParam
     * @return
     */
    @Transactional
    public boolean recordActionRepair(RecordCourse recordCourseParam) {

        try {
            RecordCourse recordCourse = recordCourseMapper.selectById(recordCourseParam.getId());
            if (recordCourse.getIsDeductHouse().equals(1)) {
                return true;
            }

            Long studentId = recordCourse.getStudentId();
            String studentName = recordCourse.getStudentName();
            Integer courseType = recordCourse.getCourseType();
            Long repairId = recordCourse.getSchedulingDetailId();
            Long schoolId = recordCourse.getSchoolId();
            Long subjectsId = recordCourse.getSubjectsId();

            RepairCourse repairCourseInfo = repairCourseMapper.selectById(repairId);
            if (repairCourseInfo == null) {
                return false;
            }
            String courseTypeName = "";
            if (courseType.equals(4)) {
                courseTypeName = "(调课)";
            } else if (courseType.equals(5)) {
                courseTypeName = "(消课)";
            } else if (courseType.equals(6)) {
                courseTypeName = "(缺课补课)";
            }else if (courseType.equals(9)) {
                courseTypeName = "(临时排课)";
            }

            Integer buckleClassHouse = 3;

            Integer teaGainHour = 3;

            /*Grade grade = iGradeService.getById(repairCourseInfo.getGradeId());
            if(grade==null){
                return false;
            }
            Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                return false;
            }*/

            Long courseId = null;
            String courseName = "";
            if (repairCourseInfo.getGradeId() != null) {
                Course course = iCourseService.getById(repairCourseInfo.getGradeId());
                if (course != null) {
                    courseId = course.getId();
                    courseName = course.getName();
                }
            }

            //调课，缺课补课的大于45课时的不扣课时
            if (!courseType.equals(5) && recordCourse.getLessonType().equals(1)) {
                Quarter quarter = iQuarterService.getQuarterForYearAndNum(recordCourse.getYearPart(),recordCourse.getQuarter());
                if (quarter.getIsDeductHouse().equals(0)){
                    //请假
                    //本学期使用课程
                    Long useCount = iStudentGradeService.getStudentUseCourseCount(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSchoolId(), recordCourse.getSubjectsId(), studentId, recordCourse.getLessonType(),recordCourse.getYearClassId());
                    if (useCount >= 45) {
                        //大于45课时，请假的不添加记录
                        RecordCourse recordCourseLeave = this.getLeaveData(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId(),recordCourse.getYearClassId());
                        boolean rsBuckMoney = false;
                        if (recordCourseLeave != null) {
                            rsBuckMoney = this.greaterBuckleMoney(recordCourse, recordCourseLeave);
                        }
                        //大于45课时，请假的不添加记录
                        UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
                        recordCourseUpdateWrapper.set("is_deduct_house", 3);
                        recordCourseUpdateWrapper.set("is_deduct_money", 3);
                        recordCourseUpdateWrapper.set("remark", "已扣15课次，不需要扣课时");
                        recordCourseUpdateWrapper.eq("id", recordCourse.getId());
                        this.update(null, recordCourseUpdateWrapper);
                        return true;
                    }
                }
            }

            QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scheduling_detail_id", repairId);
            queryWrapper.eq("student_id", studentId);
            queryWrapper.eq("status", 1);
            queryWrapper.ne("is_deduct_house", 0);
            Long count = recordCourseMapper.selectCount(queryWrapper);
            Student student = studentMapper.selectById(studentId);
            if (!recordCourse.getIsDeductHouse().equals(0)) {
                return true;
            }

            Organization organizationInfo = organizationMapper.selectById(repairCourseInfo.getSchoolId());
            String schoolName = "";
            if (organizationInfo != null) {
                schoolName = organizationInfo.getName();
            }

            Staff staff = iStaffService.getById(repairCourseInfo.getTeacherId());

            Integer yearAndQuarter = Integer.parseInt(repairCourseInfo.getYearPart() + "" + repairCourseInfo.getQuarter());

            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(repairCourseInfo.getSchoolId(), studentId, repairCourseInfo.getSubjectsId(), yearAndQuarter, repairCourseInfo.getLessonType(),repairCourseInfo.getYearClassId());

            if (residueCourseCount < buckleClassHouse) {
                RecordError recordError = new RecordError();
                recordError.setRecordCourseId(repairCourseInfo.getGradeId());
                recordError.setCourseId(courseId);
                recordError.setSchoolId(repairCourseInfo.getSchoolId());
                recordError.setStudentId(studentId);
                recordError.setContent("调课、消课、缺课补课，此学生：" + student.getName() + ",课程：" + courseName + "剩余课时不足：" + buckleClassHouse);
                iRecordErrorService.save(recordError);
                //此学生该课程没有可用课时
                return false;
            }

            //设置是否需要改为结课
            ReadingStatusEnum readingStatusEnum = ReadingStatusEnum.IN_READING;
            //请假未补数量
            Integer lackCount = 0;
            try {
                lackCount = recordCourseMapper.getLackCount(repairCourseInfo.getYearPart(), repairCourseInfo.getQuarter(), studentId, repairCourseInfo.getSubjectsId(), repairCourseInfo.getLessonType());
            } catch (Exception e) {
            }

            if (residueCourseCount == buckleClassHouse && lackCount.equals(0)) {
                readingStatusEnum = ReadingStatusEnum.FINISH;
            }

            List<OrderDetail> orderDetailList = orderDetailMapper.orderDetailListForSubjects(repairCourseInfo.getSchoolId(), studentId, repairCourseInfo.getSubjectsId(), yearAndQuarter, repairCourseInfo.getLessonType(),repairCourseInfo.getYearClassId());

            Integer diffClassHosue = buckleClassHouse;//还差多少课时

            Integer teaGainHourAll = 0;//老师得课时总课时
            BigDecimal teaGainMoneyAll = new BigDecimal(0);

            BigDecimal buckleClassMoneyAll = new BigDecimal(0);
            BigDecimal buckleClassHourAll = new BigDecimal(0);


            if (recordCourse == null) {
                recordCourse = new RecordCourse();
                //设置id
                //Long recordCourseId = idWorker.nextId();
                recordCourse.setId(idWorker.nextId());
            }

            //老师课时获得金额
            BigDecimal courseInMoney = staff.getCourseInMoney();
            BigDecimal courseInCount = new BigDecimal(staff.getCourseInCount());
            if (courseInCount.compareTo(new BigDecimal(0)) <= 0) {
                return false;
            }

            iRecordCostService.removeById(recordCourse.getId());//先删除详情
            Long lastOrderDetailId = null;

            //获取使用的请假次数
            Integer useLeaveCount = 0;
            if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                useLeaveCount = recordCourseMapper.getUseLeaveCount(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getLessonType());
            }

            for (OrderDetail orderDetail : orderDetailList) {
                if (diffClassHosue == 0) {
                    continue;
                }
                CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
                if (coursePricing == null) {
                    //此学生数据异常
                    RecordError recordError = new RecordError();
                    recordError.setRecordCourseId(courseId);
                    recordError.setCourseId(courseId);
                    recordError.setSchoolId(repairCourseInfo.getSchoolId());
                    recordError.setStudentId(studentId);
                    recordError.setContent("此学生课程价格数据异常：" + orderDetail.getCoursePriceId());
                    iRecordErrorService.save(recordError);
                    continue;
                }

                Integer userClassHouse = 0;//本次使用课时
                //本次要扣的课时大于等于剩余课时
                if (diffClassHosue > orderDetail.getResidueCourseCount()) {
                    userClassHouse = orderDetail.getResidueCourseCount();
                    diffClassHosue = diffClassHosue - orderDetail.getResidueCourseCount();
                } else {
                    userClassHouse = diffClassHosue;
                    diffClassHosue = 0;
                }

                RecordCost recordCost = new RecordCost();
                recordCost.setId(idWorker.nextId());
                recordCost.setRecordCourseId(recordCourse.getId());
                recordCost.setOrderDetailId(orderDetail.getId());

                lastOrderDetailId = orderDetail.getId();

                /**
                 * 本次使用金额 = 扣课时金额 + 服务费 + 材料费
                 */
                BigDecimal buckleClassMoneyOther = new BigDecimal("0");

                //本次扣多少个课时
                BigDecimal stuDeductHour = new BigDecimal(userClassHouse);
                //学生此次扣课时使用金额
                BigDecimal buckleClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3), BigDecimal.ROUND_HALF_UP));

                buckleClassMoneyOther = buckleClassMoneyOther.add(buckleClassMoney);

                //缺课未补的金额
                BigDecimal lackMoney = recordCourseLackMapper.getAllBucklemoneyForOrderDetailId(orderDetail.getId());
                //BigDecimal lackMoney = BigDecimal.ZERO;
                BigDecimal residuePrice = orderDetail.getResiduePrice();//剩余金额
                if (residuePrice.compareTo(BigDecimal.ZERO) < 0)
                    residuePrice = new BigDecimal(0);

                /**
                 * compareTo 反回1 表示大于，0等于，-1小于
                 * 如果此次扣除金额大于剩余金额，则改为使用剩余金额
                 */
                //最后一次课
                if (userClassHouse == orderDetail.getResidueCourseCount()) {
                    if(lackMoney.compareTo(BigDecimal.ZERO)>0){
                        if (residuePrice.subtract(lackMoney).compareTo(buckleClassMoney)>0){
                            buckleClassMoney = residuePrice.subtract(lackMoney);
                        }else {
                            if (residuePrice.compareTo(buckleClassMoney)<0){
                                buckleClassMoney = residuePrice;
                            }
                        }
                    }else {
                        //使用可是等于剩余课时
                        buckleClassMoney = residuePrice;
                    }
                    buckleClassMoneyOther = buckleClassMoney;
                } else if (buckleClassMoneyOther.compareTo(residuePrice) > 0) {
                    //本次使用金额大于剩余金额
                    buckleClassMoney = residuePrice;
                    buckleClassMoneyOther = buckleClassMoney;
                }else if (orderDetail.getResidueCourseCount().compareTo(buckleClassHouse) == 0) {
                    if(lackMoney.compareTo(BigDecimal.ZERO)>0){
                        if (residuePrice.subtract(lackMoney).compareTo(buckleClassMoney)>0){
                            buckleClassMoney = residuePrice.subtract(lackMoney);
                        }else {
                            if (residuePrice.compareTo(buckleClassMoney)<0){
                                buckleClassMoney = residuePrice;
                            }
                        }
                    }else {
                        //本次使用金额大于剩余金额
                        buckleClassMoney = residuePrice;
                    }
                    buckleClassMoneyOther = buckleClassMoney;
                }
                buckleClassHourAll = buckleClassHourAll.add(stuDeductHour);
                buckleClassMoneyAll = buckleClassMoneyAll.add(buckleClassMoney);

                //BigDecimal teaGainHour = new BigDecimal(grade.getTeaGainHour());//班级上一节课，老师得课时
                //BigDecimal teaGainMoney = teaGainHour.divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);

                recordCost.setBuckleClassHouse(userClassHouse);

                Integer teacherGetClassHosue = (userClassHouse / 3) * teaGainHour;//教师得多少课时

                //BigDecimal teaGainMoney = new BigDecimal(teacherGetClassHosue).divide(courseInCount,BigDecimal.ROUND_HALF_UP).multiply(courseInMoney);
                BigDecimal teaGainMoney = new BigDecimal(0);
                //镇级
                if (recordCourse.getSchoolId() != null && recordCourse.getSchoolId().equals(1697088501396127745L)) {
                    teaGainMoney = new BigDecimal(17);
                } else {
                    teaGainMoney = new BigDecimal(20);
                }

                teaGainHourAll = teaGainHourAll + teacherGetClassHosue;
                teaGainMoneyAll = teaGainMoneyAll.add(teaGainMoney);
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    recordCost.setBuckleClassMoney(buckleClassMoney);//本次扣课时金额
                    recordCost.setTeacherGetHouse(userClassHouse);//老师得课时
                    recordCost.setTeacherGetMoney(teaGainMoney);//老师得金额
                }

                //全新订单里的使用课时，剩余课时，剩余金额，使用金额
                /**
                 使用课时：use_course_count
                 上课累计使用金额：use_price
                 剩余课时：residue_course_count
                 剩余金额：residue_price
                 */
                //扣课时
                //orderDetailUpdateWrapper.eq("id",orderDetail.getId());
                Integer useCourseCountForOrder = orderDetail.getUseCourseCount() + userClassHouse;
                orderDetail.setUseCourseCount(useCourseCountForOrder);//累计使用课时

                Integer residueCourseCountForUse = orderDetail.getResidueCourseCount() - userClassHouse;
                orderDetail.setResidueCourseCount(residueCourseCountForUse);//剩余课时
                //到课
                if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                    orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
                    orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额
                } else {
                    if (recordCourse.getCourseType().equals(4) && useLeaveCount > 2) {//因为是先添加了请假数据，因为这里是大于2
                        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
                        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoneyOther));//剩余金额
                    }
                }

                orderDetailMapper.updateById(orderDetail);

                //UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
                //recordCostUpdateWrapper.eq("id",recordCost.getId());
                iRecordCostService.save(recordCost);

                //更新分班里使用的课时
                QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
                studentGradeQueryWrapper.eq("order_detail_id", orderDetail.getId());
                studentGradeQueryWrapper.eq("status", 1);
                studentGradeQueryWrapper.eq("deleted", 0);
                studentGradeQueryWrapper.eq("reading_status", 1);
                studentGradeQueryWrapper.eq("lesson_type", repairCourseInfo.getLessonType());
                studentGradeQueryWrapper.eq("grade_id", repairCourseInfo.getGradeId());
                studentGradeQueryWrapper.last("limit 1");
                StudentGrade studentGrade = iStudentGradeService.getOne(studentGradeQueryWrapper);
                if (studentGrade == null) {
                    studentGrade = iStudentGradeService.getLastStudentGradeForOrderDetailId(schoolId, orderDetail.getStudentId(), subjectsId, recordCourse.getYearPart(), recordCourse.getQuarter(), repairCourseInfo.getLessonType());
                }

                if (studentGrade != null) {
                    Integer useCourseCount = studentGrade.getUseCourseCount() + userClassHouse;//使用课时
                    studentGrade.setUseCourseCount(useCourseCount);
                    studentGrade.setReadingStatus(readingStatusEnum);
                    iStudentGradeService.updateById(studentGrade);
                    recordCourse.setStudentGradeId(studentGrade.getId());
                }

            }
            recordCourse.setBuckleClassHouse(Integer.parseInt(buckleClassHourAll.toString()));
            recordCourse.setOrderDetailId(lastOrderDetailId);
            recordCourse.setIsDeductHouse(1);
            recordCourse.setDeductType(1);//扣课时方式，0未知，1自动，2是手动
            //到课
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                recordCourse.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourse.setTeacherGetHouse(Integer.parseInt(teaGainHourAll.toString()));
                recordCourse.setTeacherGetMoney(teaGainMoneyAll);
                recordCourse.setIsDeductMoney(1);
            } else {
                if (recordCourse.getCourseType().equals(4) && useLeaveCount > 2) {
                    recordCourse.setBuckleClassMoney(buckleClassMoneyAll);
                    recordCourse.setTeacherGetHouse(Integer.parseInt(teaGainHourAll.toString()));
                    recordCourse.setTeacherGetMoney(teaGainMoneyAll);
                    recordCourse.setIsDeductMoney(1);
                    recordCourse.setUseLeaveNum(1);
                    recordCourse.setDeductType(4);
                } else {
                    recordCourse.setIsDeductMoney(0);
                }
            }

            recordCourse.setRemark("");
            recordCourse.setUseLeaveNum(repairCourseInfo.getUseLeaveNum());

            //UpdateWrapper<RecordCourse> recordCourseUpdateWrapper = new UpdateWrapper<>();
            //recordCourseUpdateWrapper.eq("scheduling_detail_id",schedulingDetailId);
            //recordCourseUpdateWrapper.eq("student_id",recordCourse.getStudentId());

            if (courseType.equals(4)) {
                //调课，后面补加的所以加上错误捕捉
                try {
                    CourseSchedulingDetail courseSchedulingDetailPd = iCourseSchedulingDetailService.getCourseSchedulingDetailById(repairCourseInfo.getOutSchedulingDetailId());
                    if (courseSchedulingDetailPd != null) {
                        LocalDate oldSchoolDate = courseSchedulingDetailPd.getSchoolDate();
                        recordCourse.setOldSchoolDate(oldSchoolDate);
                        recordCourse.setLessonNum(courseSchedulingDetailPd.getLessonNum());
                    }
                } catch (Exception e) {
                }
            }else if (courseType.equals(6)){
                //缺课补课
                LackCourseLog lackCourseLog = iLackCourseLogService.getById(repairCourseInfo.getRecordCourseId());
                if (lackCourseLog!=null){
                    recordCourse.setLessonNum(lackCourseLog.getLessonNum());
                }
            }

            if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE)) {
                recordCourse.setUseLeaveNum(1);
            } else {
                recordCourse.setUseLeaveNum(repairCourseInfo.getUseLeaveNum());//设置是否是请假次数添加一次
            }


            this.updateById(recordCourse);
            //recordCourseList.add(recordCourse);

            if (!recordCourse.getStatus().equals(StatusRecordEnum.REACH)) {
                //缺课的金额暂时保存
                RecordCourseLack recordCourseLack = new RecordCourseLack();
                recordCourseLack.setId(recordCourse.getId());
                recordCourseLack.setOrderDetailId(recordCourse.getOrderDetailId());
                recordCourseLack.setBuckleClassHouse(recordCourse.getBuckleClassHouse());
                recordCourseLack.setBuckleClassMoney(buckleClassMoneyAll);
                recordCourseLack.setTeacherGetHouse(teaGainHourAll);
                recordCourseLack.setTeacherGetMoney(teaGainMoneyAll);
                iRecordCourseLackService.saveOrUpdate(recordCourseLack);
            }

            //到课，发送微信提醒
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("school_id", repairCourseInfo.getSchoolId());
            studentGradeQueryWrapper.eq("student_id", student.getId());
            studentGradeQueryWrapper.eq("subjects_id", repairCourseInfo.getSubjectsId());
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("course_status", 1);//课时是否异常，异常的不推送家长,正常：1

            Long courseStatusCount = iStudentGradeService.count(studentGradeQueryWrapper);
            if (recordCourse.getStatus().equals(StatusRecordEnum.REACH) && recordCourse.getLessonType().equals(1) || (recordCourse.getLessonType().equals(1) && recordCourse.getCourseType().equals(4) && useLeaveCount > 2)) {
                if (courseStatusCount > 0) {
                    StringBuilder first = new StringBuilder();
                    first.append("(").append(schoolName).append(")").append("新增上课记录，请查看");
                    String keyword1 = student.getName();
                    StringBuilder keyword2 = new StringBuilder();
                    keyword2.append(repairCourseInfo.getSchoolDate()).append(" ").append(repairCourseInfo.getTimeStart()).append("-").append(repairCourseInfo.getTimeEnd());
                    StringBuilder remark = new StringBuilder();
                    //Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;
                    //remark.append("考勤状态为“上课"+courseTypeName+"”，").append("消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时");
                    StringBuilder keyword3 = new StringBuilder();

                    //keyword3.append("考勤状态为“上课"+courseTypeName+"”，消耗").append(buckleClassHouse).append("课时");
                    Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;//剩余课时
                    StringBuilder keyword4 = new StringBuilder();
                    //keyword4.append(residueCourseCountNew).append("课时").append(",如有疑问请及时与老师联系");

                    if (recordCourse.getStatus().equals(StatusRecordEnum.LEAVE) && useLeaveCount > 2) {
                        keyword3.append("考勤状态为“未到" + courseTypeName + "”，消耗").append(buckleClassHouse).append("课时");
                        keyword4.append(residueCourseCountNew).append("课时").append(",超过请假次数课时已扣");
                    } else {
                        keyword3.append("考勤状态为“上课" + courseTypeName + "”，消耗").append(buckleClassHouse).append("课时");
                        keyword4.append(residueCourseCountNew).append("课时").append(",如有疑问请及时与老师联系");
                    }

                    //StringBuilder remark = new StringBuilder();
                    //remark.append("考勤状态为“上课"+courseTypeName+"”，").append("消耗“"+buckleClassHouse+"”课时，剩余“"+residueCourseCountNew+"”课时");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(recordCourse.getStudentId());
                    iWecharsBindService.wxPushUseCourseHouse(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), keyword4.toString(), remark.toString(), repairCourseInfo.getId() + "" + student.getId());
                }
            } else {
                if (courseStatusCount > 0 && recordCourse.getLessonType().equals(1)) {
                    StringBuilder first = new StringBuilder();
                    //小明家长，您好！小明xxxx年xx月xx日未能准时到校签到上课！
                    first.append("" + student.getName() + "家长，您好！" + student.getName() + "" + repairCourseInfo.getSchoolDate() + "未能准时到校签到上课！");
                    String keyword1 = student.getName();
                    StringBuilder keyword2 = new StringBuilder();

                    //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                    String gradeName = this.replaceGradeNameForStudentIdAndSubjectsId(repairCourseInfo.getYearPart(),repairCourseInfo.getQuarter(),repairCourseInfo.getStudentId(),repairCourseInfo.getSubjectsId());

                    keyword2.append(gradeName);
                    StringBuilder keyword3 = new StringBuilder();
                    //keyword3.append(repairCourseInfo.getStartDateTime().toString().replace("T", " "));
                    //keyword2.append(repairCourseInfo.getSchoolDate()).append(" ").append(repairCourseInfo.getTimeStart()).append("-").append(repairCourseInfo.getTimeEnd()).append(" 每个学期只能请假2次");

                    if (useLeaveCount <= 2 && useLeaveCount > 0) {
                        keyword3.append(repairCourseInfo.getStartDateTime().toString().replace("T", " ") + " 已用" + useLeaveCount + "次请假次数");
                    } else {
                        //正常情况下不会执行到这里，正常情况使用大于两次是使用课时消耗上面的条件
                        keyword3.append(repairCourseInfo.getStartDateTime().toString().replace("T", " ") + " 每个学期只能请假2次");
                    }


                    StringBuilder remark = new StringBuilder();
                    Integer residueCourseCountNew = residueCourseCount - buckleClassHouse;
                    //remark.append("考勤状态为“缺课"+courseTypeName+"”，").append("课时已扣，消耗“" + buckleClassHouse + "”课时，剩余“" + residueCourseCountNew + "”课时，请联系任课老师补课");
                    first.append("，考勤状态为“缺课" + courseTypeName + "”，").append("课时已扣，消耗“" + buckleClassHouse + "”课时，剩余“" + residueCourseCountNew + "”课时，请联系任课老师补课");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(recordCourse.getStudentId());
                    iWecharsBindService.wxPushMissAClass(opendIdList, first.toString(), keyword1, keyword2.toString(), keyword3.toString(), remark.toString(), repairCourseInfo.getId() + "" + student.getId());
                }
            }
            return true;
        } catch (Exception e) {
            System.out.println("recordActionError:" + e.getMessage());
            return false;
        }
    }

    /**
     * 缺课学生补课扣除金额
     *
     * @param repairCourseId 按排的补课id
     * @return
     */
    @Transactional
    public boolean repairBuckleMoney(Long repairCourseId) {

        //获取出按排的补课信息
        RepairCourse repairCourse = repairCourseMapper.selectById(repairCourseId);
        if (repairCourse == null)
            return false;
        //缺课记上课记录
        RecordCourse recordCourseOld = recordCourseMapper.selectById(repairCourse.getRecordCourseId());
        if (recordCourseOld == null)
            return false;
        /*if (recordCourseOld.getTeacherGetMoney().compareTo(BigDecimal.ZERO) == 0){
            return false;
        }*/

        //获取出记上课信息
        RecordCourse recordCourse = recordCourseMapper.selectOne(new QueryWrapper<RecordCourse>().eq("scheduling_detail_id", repairCourse.getId()).last("limit 1"));
        //已扣过的，不再扣
        if (recordCourseOld.getIsDeductMoney().equals(1)) {
            return true;
        }
        if (recordCourse == null)
            return false;
        if (recordCourse.getCourseType() != 3)
            return false;

        RecordCourseLack recordCourseLack = recordCourseLackMapper.selectById(recordCourseOld.getId());
        if (recordCourseLack == null)
            return false;

        OrderDetail orderDetail = orderDetailMapper.selectById(recordCourseLack.getOrderDetailId());
        if (orderDetail == null)
            return false;

        BigDecimal buckleClassMoney = recordCourseLack.getBuckleClassMoney();
        if (orderDetail.getResiduePrice().compareTo(recordCourseLack.getBuckleClassMoney()) < 0) {
            buckleClassMoney = orderDetail.getResiduePrice();
        }

        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoney));//剩余金额
        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
        orderDetailMapper.updateById(orderDetail);

        //更新记录
        recordCourse.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCourse.setStudentGradeId(recordCourseOld.getStudentGradeId());
        recordCourse.setIsDeductHouse(1);
        recordCourse.setIsDeductMoney(1);
        recordCourse.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().add(buckleClassMoney));
        recordCourse.setTeacherGetMoney(recordCourse.getTeacherGetMoney().add(recordCourseLack.getTeacherGetMoney()));
        recordCourse.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        //recordCourse.setByRecordId(recordCourseOld.getId());
        recordCourseMapper.updateById(recordCourse);

        //更新原来的数据
        recordCourseOld.setBuckleClassHouse(0);
        recordCourseOld.setBuckleClassMoney(new BigDecimal(0));
        recordCourseOld.setTeacherGetHouse(0);
        recordCourseOld.setTeacherGetMoney(new BigDecimal(0));
        recordCourseOld.setIsRepair(1);
        recordCourseOld.setIsDeductHouse(1);
        recordCourseOld.setIsDeductMoney(1);
        recordCourseOld.setStatus(StatusRecordEnum.LEAVE);//请假
        recordCourseMapper.updateById(recordCourseOld);

        /*UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
        recordCostUpdateWrapper.set("buckle_class_house",0);
        recordCostUpdateWrapper.eq("record_course_id",recordCourseOld.getId());
        iRecordCostService.update(null,recordCostUpdateWrapper);*/
        //删除原来的数据
        iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourseOld.getId()));

        //添加记录详情
        RecordCost recordCostNew = new RecordCost();
        //BeanUtils.copyProperties(recordCostOld,recordCostNew);
        recordCostNew.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCostNew.setBuckleClassMoney(buckleClassMoney);
        recordCostNew.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
        recordCostNew.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCostNew.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCostNew.setId(idWorker.nextId());
        recordCostNew.setRecordCourseId(recordCourse.getId());
        iRecordCostService.save(recordCostNew);

        recordCourseLack.setIsDeductMoney(1);
        recordCourseLack.setBuckleClassMoney(buckleClassMoney);
        recordCourseLackMapper.updateById(recordCourseLack);

        //安排补课的数据设置为已补课状态（已扣课时）
        repairCourse.setStatus(1);
        repairCourseMapper.updateById(repairCourse);

        return true;
    }

    /**
     * 正常排课的添加请假（没有到课的数据）
     *
     * @param schedulingDetailId
     * @param studentId
     * @param buckleHouse
     * @param status
     * @param type
     * @param courseType
     * @param quarterNow
     * @return
     */
    @Override
    @Transactional
    public RecordCourse addLeaveData(Long schedulingDetailId, Long studentId, Integer buckleHouse, StatusRecordEnum status, Integer type, Integer courseType, Quarter quarterNow, Integer yearClassId) {
        try {
            QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scheduling_detail_id", schedulingDetailId);
            queryWrapper.eq("student_id", studentId);
            queryWrapper.last("limit 1");
            RecordCourse recordCourse = recordCourseMapper.selectOne(queryWrapper);
            //已经添加过的，直接返回
            if (recordCourse != null) {
                return recordCourse;
            }

            CourseSchedulingDetail courseSchedulingDetailInfo = iCourseSchedulingDetailService.getById(schedulingDetailId);
            if (courseSchedulingDetailInfo == null) {
                return null;
            }
            /*Grade grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());
            Grade oldGrade = new Grade();
            //精品课所在班级（按日程排课,没有班级，要添加上精品课所在班级）
            StudentGrade studentGrade = iStudentGradeService.getLastForMaxId(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSubjectsId(), studentId, 1);
            if (studentGrade != null) {
                oldGrade = iGradeService.getById(studentGrade.getGradeId());
                if (oldGrade == null){
                    oldGrade = new Grade();
                    oldGrade.setId(studentGrade.getGradeId());
                }
            }*/

            Grade grade = null;
            Grade oldGrade = new Grade();
            if (courseSchedulingDetailInfo.getGradeId()!=null){
                grade = iGradeService.getById(courseSchedulingDetailInfo.getGradeId());
            }
            if (grade==null){
                grade = new Grade();
            }

            //精品课所在班级（按日程排课,没有班级，要添加上精品课所在班级）
            StudentGrade studentGrade = iStudentGradeService.getLastForMaxId(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSubjectsId(), studentId, 1,grade.getYearClassId().getKey());
            if (studentGrade != null) {
                oldGrade = iGradeService.getById(studentGrade.getGradeId());
                if (oldGrade == null){
                    oldGrade = new Grade();
                    oldGrade.setId(studentGrade.getGradeId());
                }
            }


            /*if(grade==null){
                return null;
            }
            Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                return null;
            }*/
            Integer yearAndQuarter = Integer.parseInt(courseSchedulingDetailInfo.getYearPart() + "" + courseSchedulingDetailInfo.getQuarter());
            //使用本学期使用课时
            Long useCount = iStudentGradeService.getStudentUseCourseCount(courseSchedulingDetailInfo.getYearPart(), courseSchedulingDetailInfo.getQuarter(), courseSchedulingDetailInfo.getSchoolId(), courseSchedulingDetailInfo.getSubjectsId(), studentId, courseSchedulingDetailInfo.getLessonType(),yearClassId);
            //状态不为消课的,并且为精品课
            if (!courseType.equals(5) && courseSchedulingDetailInfo.getLessonType().equals(1)) {
                Quarter quarter = iQuarterService.getQuarterForYearAndNum(courseSchedulingDetailInfo.getYearPart(),courseSchedulingDetailInfo.getQuarter());
                //超过15次课，是否继续扣课时
                if (quarter.getIsDeductHouse().equals(0)){
                    if (useCount >= 45) {
                        //请假，请假的不添加数据，直接返回
                        //大于45课时，请假的不添加记录
                        return null;
                    }
                }
            }
            Student student = studentMapper.selectById(studentId);
            //Staff staff = iStaffService.getById(courseSchedulingDetailInfo.getTeacherId());
            recordCourse = new RecordCourse();
            recordCourse.setId(idWorker.nextId());

            recordCourse.setLessonType(courseSchedulingDetailInfo.getLessonType());
            recordCourse.setLessonNum(courseSchedulingDetailInfo.getLessonNum());//课次
            recordCourse.setSchedulingDetailId(schedulingDetailId);
            recordCourse.setStudentId(studentId);
            recordCourse.setStudentName(student.getName());

            recordCourse.setStatus(status);

            recordCourse.setType(type);
            recordCourse.setCourseType(courseType);
            recordCourse.setSchoolId(courseSchedulingDetailInfo.getSchoolId());
            recordCourse.setSchoolName(courseSchedulingDetailInfo.getSchoolName());
            recordCourse.setGradeId(grade.getId());
            recordCourse.setGradeName(grade.getName());
            recordCourse.setTeacherId(courseSchedulingDetailInfo.getTeacherId());
            recordCourse.setTeacherName(courseSchedulingDetailInfo.getTeacherName());
            recordCourse.setOldGradeId(oldGrade.getId());
            recordCourse.setOldTeacherId(oldGrade.getTeacherId());
            recordCourse.setYearClassId(grade.getYearClassId().getKey());


            recordCourse.setClassRoomId(courseSchedulingDetailInfo.getClassRoomId());
            recordCourse.setClassRoomName(courseSchedulingDetailInfo.getClassRoomName());
            recordCourse.setCourseId(courseSchedulingDetailInfo.getCourseId());
            recordCourse.setCourseName(courseSchedulingDetailInfo.getCourseName());
            recordCourse.setSubjectsId(courseSchedulingDetailInfo.getSubjectsId());
            recordCourse.setSubjectsName(courseSchedulingDetailInfo.getSubjectsName());
            recordCourse.setSchoolDate(courseSchedulingDetailInfo.getSchoolDate());
            recordCourse.setTimeStart(courseSchedulingDetailInfo.getTimeStart());
            recordCourse.setTimeEnd(courseSchedulingDetailInfo.getTimeEnd());
            recordCourse.setStartDateTime(LocalDateTime.parse(recordCourse.getSchoolDate() + "T" + recordCourse.getTimeStart() + ":00"));
            recordCourse.setEndDateTime(LocalDateTime.parse(recordCourse.getSchoolDate() + "T" + recordCourse.getTimeEnd() + ":00"));
            recordCourse.setYearAndQuarter(yearAndQuarter);
            recordCourse.setYearPart(courseSchedulingDetailInfo.getYearPart());
            recordCourse.setQuarter(courseSchedulingDetailInfo.getQuarter());
            recordCourse.setUseLeaveNum(1);//请假的这里设置为使用一次
            if (courseType.equals(4)) {
                //recordCourse.setRepairId(recordCourse.getSchedulingDetailId());//班级调的的把id赋值给repairId
                //调课，后面补加的所以加上错误捕捉
                try {
                    CourseSchedulingDetail courseSchedulingDetailPd = iCourseSchedulingDetailService.getCourseSchedulingDetailById(courseSchedulingDetailInfo.getPid());
                    if (courseSchedulingDetailPd != null) {
                        LocalDate oldSchoolDate = courseSchedulingDetailPd.getSchoolDate();
                        recordCourse.setOldSchoolDate(oldSchoolDate);
                    }
                } catch (Exception e) {
                }
            }
            //分多年级数据有误，注释掉
            /*if (courseSchedulingDetailInfo.getLessonType()!=null && courseSchedulingDetailInfo.getLessonType().equals(1)) {
                //获取精品课最后一次排课
                StudentGrade studentGradeLast = iStudentGradeService.getLastOne(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getSubjectsId(), recordCourse.getStudentId(), 1);
                if (studentGradeLast != null) {
                    recordCourse.setOldGradeId(studentGradeLast.getGradeId());
                    Grade gradeLast = iGradeService.getById(studentGradeLast.getGradeId());
                    if (gradeLast != null) {
                        Staff staffOld = iStaffService.getById(gradeLast.getTeacherId());
                        recordCourse.setOldTeacherId(gradeLast.getTeacherId());
                        recordCourse.setYearClassId(gradeLast.getYearClassId().getKey());
                        recordCourse.setGradeId(gradeLast.getId());
                        recordCourse.setGradeName(gradeLast.getName());
                        recordCourse.setTeacherId(gradeLast.getTeacherId());
                        recordCourse.setTeacherName(staffOld.getName());
                        recordCourse.setOldGradeId(gradeLast.getId());
                    }
                }
            }*/

            //recordCourse.setUseLeaveNum(1);//设置是否是请假次数添加一次,注释掉，在扣课时里添加
            this.save(recordCourse);
            return recordCourse;
        } catch (Exception e) {
            System.out.println("recordActionError:" + e.getMessage());
            return null;
        }
    }

    public RecordCourse addLeaveDataForRepair(Long repairId, Long studentId, Integer buckleHouse, StatusRecordEnum status, Integer type, Integer courseType, Integer isSignIn) {
        try {
            RepairCourse repairCourseInfo = repairCourseMapper.selectById(repairId);
            if (repairCourseInfo == null) {
                return null;
            }
            QueryWrapper<RecordCourse> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("scheduling_detail_id", repairId);
            queryWrapper.eq("student_id", studentId);
            queryWrapper.last("limit 1");
            RecordCourse recordCourse = recordCourseMapper.selectOne(queryWrapper);
            if (recordCourse != null) {
                //已经记上课过的,直接返回成功
                return recordCourse;
            }
            Student student = studentMapper.selectById(studentId);

            Integer buckleClassHouse = buckleHouse;

            String courseTypeName = "";
            if (courseType.equals(4)) {
                courseTypeName = "(调课)";
            } else if (courseType.equals(5)) {
                courseTypeName = "(消课)";
            } else if (courseType.equals(6)) {
                courseTypeName = "(缺课补课)";
            }else if (courseType.equals(9)) {
                courseTypeName = "(临时排课)";
            }
            /*Grade grade = iGradeService.getById(repairCourseInfo.getGradeId());
            if(grade==null){
                return null;
            }
            Course course = iCourseService.getById(grade.getCourseId());
            if(course==null){
                return null;
            }*/

            Long courseId = null;
            String courseName = "";
            if (repairCourseInfo.getGradeId() != null) {
                Course course = iCourseService.getById(repairCourseInfo.getGradeId());
                if (course != null) {
                    courseId = course.getId();
                    courseName = course.getName();
                }
            }


            //调课，缺课补课的大于45课时的不扣课时
            if (!courseType.equals(5)) {
                Quarter quarter = iQuarterService.getQuarterForYearAndNum(repairCourseInfo.getYearPart(), repairCourseInfo.getQuarter());
                if (quarter.getIsDeductHouse().equals(0)){
                    //请假
                    //本学期使用课程
                    Long useCount = iStudentGradeService.getStudentUseCourseCount(repairCourseInfo.getYearPart(), repairCourseInfo.getQuarter(), repairCourseInfo.getSchoolId(), repairCourseInfo.getSubjectsId(), studentId, repairCourseInfo.getLessonType(),repairCourseInfo.getYearClassId());
                    if (useCount >= 45 && repairCourseInfo.getLessonType().equals(1)) {
                        //大于45课时，请假的不添加记录
                        return null;
                    }
                }
            }

            Organization organizationInfo = organizationMapper.selectById(repairCourseInfo.getSchoolId());
            String schoolName = "";
            if (organizationInfo != null) {
                schoolName = organizationInfo.getName();
            }

            Staff staff = iStaffService.getById(repairCourseInfo.getTeacherId());

            Integer yearAndQuarter = Integer.parseInt(repairCourseInfo.getYearPart() + "" + repairCourseInfo.getQuarter());

            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(repairCourseInfo.getSchoolId(), studentId, repairCourseInfo.getSubjectsId(), yearAndQuarter, repairCourseInfo.getLessonType(),repairCourseInfo.getYearClassId());

            Grade oldGrade = new Grade();//精品课所在班级（按日程排课）

            Grade grade = null;
            StudentGrade studentGrade = iStudentGradeService.getLastForMaxId(repairCourseInfo.getYearPart(), repairCourseInfo.getQuarter(), repairCourseInfo.getSubjectsId(), studentId, repairCourseInfo.getLessonType(),repairCourseInfo.getYearClassId());
            if (studentGrade != null) {
                grade = iGradeService.getById(studentGrade.getGradeId());
            }
            if (grade==null){
                grade = new Grade();
            }
            //精品课所在班级（按日程排课,没有班级，要添加上精品课所在班级）
            StudentGrade studentGradeBoutique = iStudentGradeService.getLastForMaxId(repairCourseInfo.getYearPart(), repairCourseInfo.getQuarter(), repairCourseInfo.getSubjectsId(), studentId, 1,repairCourseInfo.getYearClassId());
            if (studentGradeBoutique != null) {
                oldGrade = iGradeService.getById(studentGradeBoutique.getGradeId());
                if (oldGrade == null){
                    oldGrade = new Grade();
                    oldGrade.setId(studentGrade.getGradeId());
                }
            }

            recordCourse = new RecordCourse();
            recordCourse.setId(idWorker.nextId());
            recordCourse.setLessonType(repairCourseInfo.getLessonType());
            recordCourse.setSchedulingDetailId(repairId);
            recordCourse.setStudentId(studentId);
            recordCourse.setStudentName(student.getName());
            recordCourse.setType(type);
            recordCourse.setCourseType(courseType);
            recordCourse.setSchoolId(repairCourseInfo.getSchoolId());
            recordCourse.setSchoolName(schoolName);
            recordCourse.setOldGradeId(oldGrade.getId());
            recordCourse.setOldTeacherId(oldGrade.getTeacherId());

            //缺课算带班老师的，因此这里设置为带班老师
            if (recordCourse.getLessonType().equals(1)){
                recordCourse.setTeacherId(oldGrade.getTeacherId());
                recordCourse.setGradeId(oldGrade.getId());
                recordCourse.setGradeName(oldGrade.getName());
            }else {
                recordCourse.setTeacherId(grade.getTeacherId());
                recordCourse.setGradeId(grade.getId());
                recordCourse.setGradeName(grade.getName());
            }


            Staff teacherInfo = iStaffService.getById(oldGrade.getTeacherId());
            if (teacherInfo != null) {
                recordCourse.setTeacherName(teacherInfo.getName());
            }

            recordCourse.setLessonNum(repairCourseInfo.getLessonNum());

            if (oldGrade.getYearClassId() != null) {
                recordCourse.setYearClassId(oldGrade.getYearClassId().getKey());
            }


            recordCourse.setClassRoomId(repairCourseInfo.getRoomId());
            recordCourse.setClassRoomName(repairCourseInfo.getRoomName());
            recordCourse.setCourseId(courseId);
            recordCourse.setCourseName(courseName);
            recordCourse.setSubjectsId(repairCourseInfo.getSubjectsId());
            recordCourse.setSubjectsName(repairCourseInfo.getSubjectsName());
            recordCourse.setYearAndQuarter(yearAndQuarter);
            recordCourse.setYearPart(repairCourseInfo.getYearPart());
            recordCourse.setQuarter(repairCourseInfo.getQuarter());
            recordCourse.setStatus(status);
            recordCourse.setSchoolDate(repairCourseInfo.getSchoolDate());
            recordCourse.setTimeStart(repairCourseInfo.getTimeStart());
            recordCourse.setTimeEnd(repairCourseInfo.getTimeEnd());
            recordCourse.setStartDateTime(LocalDateTime.parse(recordCourse.getSchoolDate() + "T" + recordCourse.getTimeStart() + ":00"));
            recordCourse.setEndDateTime(LocalDateTime.parse(recordCourse.getSchoolDate() + "T" + recordCourse.getTimeEnd() + ":00"));
            recordCourse.setUseLeaveNum(1);
            if (courseType.equals(4)) {
                //调课，后面补加的所以加上错误捕捉
                try {
                    CourseSchedulingDetail courseSchedulingDetailPd = iCourseSchedulingDetailService.getCourseSchedulingDetailById(repairCourseInfo.getOutSchedulingDetailId());
                    if (courseSchedulingDetailPd != null) {
                        LocalDate oldSchoolDate = courseSchedulingDetailPd.getSchoolDate();
                        recordCourse.setOldSchoolDate(oldSchoolDate);
                    }
                } catch (Exception e) {
                }
            }

            //recordCourse.setUseLeaveNum(1);//设置是否是请假次数添加一次,注释掉，在扣课时里添加
            this.save(recordCourse);
            return recordCourse;
        } catch (Exception e) {
            System.out.println("recordActionError:" + e.getMessage());
            return null;
        }
    }


    public void getUnRpair(Long schoolId, Long subjectsId, Long studentId, Integer yearPart, Integer quarterNum) {
        QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
        recordCourseQueryWrapper.eq("school_id", schoolId);
        recordCourseQueryWrapper.eq("subjects_id", subjectsId);
        recordCourseQueryWrapper.eq("year_part", yearPart);
        recordCourseQueryWrapper.eq("quarter", quarterNum);
        recordCourseQueryWrapper.eq("student_id", studentId);
        recordCourseQueryWrapper.eq("is_deduct_house", 1);
        recordCourseQueryWrapper.eq("is_deduct_money", 0);
        recordCourseQueryWrapper.eq("status", 2);

        recordCourseQueryWrapper.last("limit 1");


    }


    /**
     *
     */
    public boolean pathchMoney() {
        try {
            Quarter quarterNow = iQuarterService.getNowQuarter();
            if (quarterNow == null) {
                return false;
            }
            LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
            QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
            LocalDate localDateNow = LocalDate.now();
            recordCourseQueryWrapper.eq("school_date", localDateNow);
            recordCourseQueryWrapper.lt("end_date_time", dateTimeNow);
            recordCourseQueryWrapper.eq("status", 1);
            recordCourseQueryWrapper.eq("is_deduct_house", 1);
            recordCourseQueryWrapper.eq("is_deduct_money", 0);
            recordCourseQueryWrapper.eq("is_repair", 0);
            recordCourseQueryWrapper.eq("year_part", quarterNow.getYearPart());
            recordCourseQueryWrapper.eq("quarter", quarterNow.getNum());
            recordCourseQueryWrapper.ne("course_type", 3);//不等于补课

            List<RecordCourse> recordCourseList = recordCourseMapper.selectList(recordCourseQueryWrapper);

            Integer i = 0;
            for (RecordCourse recordCourse : recordCourseList) {
                RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(recordCourse.getId());
                if (recordCourseLack != null) {
                    OrderDetail orderDetail = orderDetailMapper.selectById(recordCourseLack.getOrderDetailId());
                    if (orderDetail != null) {
                        BigDecimal buckMoney = recordCourseLack.getBuckleClassMoney();
                        if (orderDetail.getResiduePrice().compareTo(buckMoney) < 0) {
                            buckMoney = orderDetail.getResiduePrice();
                        }
                        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckMoney));
                        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckMoney));
                        orderDetailMapper.updateById(orderDetail);
                        recordCourseLack.setIsDeductMoney(1);

                        recordCourse.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
                        recordCourse.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
                        recordCourse.setBuckleClassMoney(buckMoney);
                        recordCourse.setIsDeductMoney(1);
                        recordCourseMapper.updateById(recordCourse);
                        RecordCost recordCost = iRecordCostService.getOne(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourse.getId()));

                        if (recordCost != null) {
                            recordCost.setBuckleClassMoney(buckMoney);
                            recordCost.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
                            recordCost.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
                            iRecordCostService.updateById(recordCost);
                        }
                        i++;
                    }
                }
            }

        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public Integer getRecordCountArrive(Integer yearPart, Integer quarterNum, Long studentId, Long subjectsId) {
        return recordCourseMapper.getRecordCountArrive(yearPart, quarterNum, studentId, subjectsId);
    }

    @Override
    public RecordCourse getLeaveData(Integer yearPart,
                                     Integer quarterNum,
                                     Integer lessonType,
                                     Long studentId,
                                     Long subjectsId,
                                     Integer yearClassId) {
        return recordCourseMapper.getLeaveData(yearPart, quarterNum, lessonType, studentId, subjectsId,yearClassId);
    }

    /**
     * 大于15次课的，扣除补课金额
     *
     * @return
     */
    @Override
    public boolean greaterBuckleMoney(RecordCourse recordCourse, RecordCourse recordCourseOld) {

        if (recordCourse.getIsDeductHouse().equals(1))
            return false;

        //已扣过的，不再扣
        if (recordCourseOld.getIsDeductMoney().equals(1)) {
            return false;
        }

        RecordCourseLack recordCourseLack = recordCourseLackMapper.selectById(recordCourseOld.getId());
        if (recordCourseLack == null)
            return false;

        OrderDetail orderDetail = orderDetailMapper.selectById(recordCourseLack.getOrderDetailId());
        if (orderDetail == null)
            return false;

        BigDecimal buckleClassMoney = recordCourseLack.getBuckleClassMoney();
        if (orderDetail.getResiduePrice().compareTo(recordCourseLack.getBuckleClassMoney()) < 0) {
            buckleClassMoney = orderDetail.getResiduePrice();
        }

        orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoney));//剩余金额
        orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));//上课累计使用金额
        orderDetailMapper.updateById(orderDetail);

        //更新记录
        recordCourse.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCourse.setStudentGradeId(recordCourseOld.getStudentGradeId());
        recordCourse.setCourseType(3);
        recordCourse.setIsDeductHouse(1);
        recordCourse.setIsDeductMoney(1);
        recordCourse.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCourse.setBuckleClassMoney(recordCourse.getBuckleClassMoney().add(buckleClassMoney));
        recordCourse.setTeacherGetMoney(recordCourse.getTeacherGetMoney().add(recordCourseLack.getTeacherGetMoney()));
        recordCourse.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCourse.setByRecordId(recordCourseOld.getId());//被补课id
        recordCourseMapper.updateById(recordCourse);

        //更新原来的数据
        recordCourseOld.setBuckleClassHouse(0);
        recordCourseOld.setBuckleClassMoney(new BigDecimal(0));
        recordCourseOld.setTeacherGetHouse(0);
        recordCourseOld.setTeacherGetMoney(new BigDecimal(0));
        recordCourseOld.setIsRepair(1);
        recordCourseOld.setIsDeductHouse(1);
        recordCourseOld.setIsDeductMoney(1);
        recordCourseOld.setStatus(StatusRecordEnum.LEAVE);//请假
        recordCourseOld.setRepairEndDateTime(recordCourse.getEndDateTime());
        recordCourseMapper.updateById(recordCourseOld);

        /*UpdateWrapper<RecordCost> recordCostUpdateWrapper = new UpdateWrapper<>();
        recordCostUpdateWrapper.set("buckle_class_house",0);
        recordCostUpdateWrapper.eq("record_course_id",recordCourseOld.getId());
        iRecordCostService.update(null,recordCostUpdateWrapper);*/
        //删除原来的数据
        iRecordCostService.remove(new QueryWrapper<RecordCost>().eq("record_course_id", recordCourseOld.getId()));

        //添加记录详情
        RecordCost recordCostNew = new RecordCost();
        //BeanUtils.copyProperties(recordCostOld,recordCostNew);
        recordCostNew.setBuckleClassHouse(recordCourseLack.getBuckleClassHouse());
        recordCostNew.setBuckleClassMoney(buckleClassMoney);
        recordCostNew.setTeacherGetMoney(recordCourseLack.getTeacherGetMoney());
        recordCostNew.setTeacherGetHouse(recordCourseLack.getTeacherGetHouse());
        recordCostNew.setOrderDetailId(recordCourseLack.getOrderDetailId());
        recordCostNew.setId(idWorker.nextId());
        recordCostNew.setRecordCourseId(recordCourse.getId());
        iRecordCostService.save(recordCostNew);

        recordCourseLack.setIsDeductMoney(1);
        recordCourseLackMapper.updateById(recordCourseLack);
        //Map<String,Object> objectMap = new HashMap<>();
        //objectMap.put("buckleHouse",recordCourse.getBuckleClassHouse());
        //objectMap.put("buckleMoney",recordCourse.getBuckleClassMoney());

        Integer leaveCount = recordCourseMapper.getLeaveCount(recordCourse.getYearPart(), recordCourse.getQuarter(), recordCourse.getLessonType(), recordCourse.getStudentId(), recordCourse.getSubjectsId());
        Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(recordCourse.getSchoolId(), recordCourse.getStudentId(), recordCourse.getSubjectsId(), recordCourse.getYearAndQuarter(), recordCourse.getLessonType(),recordCourse.getYearClassId());

        if (leaveCount.equals(0) && residueCourseCount.equals(0)) {
            UpdateWrapper<StudentGrade> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("year_part", recordCourse.getYearPart());
            updateWrapper.eq("quarter_num", recordCourse.getQuarter());
            updateWrapper.eq("student_id", recordCourse.getStudentId());
            updateWrapper.eq("subjects_id", recordCourse.getSubjectsId());
            updateWrapper.eq("reading_status", 1);
            updateWrapper.set("reading_status", 5);//结课
            iStudentGradeService.update(updateWrapper);
        }

        return true;
    }

    private String replaceGradeNameForStudentIdAndSubjectsId(Integer yearPart,Integer quarterNum,Long studentId, Long subjectsId) {
        StudentGrade studentGrade = iStudentGradeService.getLastOne(yearPart,quarterNum,subjectsId,studentId,1);
        String keyword1 = "";
        Student student = studentMapper.selectById(studentId);
        String studentName = student.getName();
        try{
            if (studentGrade!=null){
                Grade grade = iGradeService.getById(studentGrade.getGradeId());
                String gradeName = grade.getName();
                Course course = iCourseService.getById(grade.getCourseId());
                Subjects subjects = iSubjectsService.getById(course.getSubjectsId());
                Staff staff = iStaffService.getById(grade.getTeacherId());
                String teacherName = staff.getName();
                String subjectsName = subjects.getName();
                keyword1 = gradeName;
                if (keyword1.contains("【" + teacherName + "】")) {
                    keyword1 = keyword1.replace("【" + teacherName + "】", "【" + studentName + "】" + subjectsName);
                } else if (keyword1.contains("【" + subjectsName + "】")) {
                    keyword1 = keyword1.replace("【" + subjectsName + "】", "【" + studentName + "】" + subjectsName);
                } else if (keyword1.contains(teacherName)) {
                    keyword1 = keyword1.replace(teacherName, studentName);
                    keyword1 += subjectsName;
                } else {
                    keyword1 = "【" + studentName + "】" + subjectsName;
                }
            }else {
                keyword1 = "【" + studentName + "】";
            }
        }catch (Exception e){
            keyword1 = "【" + studentName + "】" + keyword1;
        }

        return keyword1;
    }

    /**
     * 删除试听超过时间未核对的数据
     * @param
     * @return
     */
    @Override
    public boolean deleteTryListenRecordCourse(Integer minusDays) {
        try {
            LocalDate nowDate = LocalDate.now();
            Quarter quarter = iQuarterService.getNowQuarter();
            QueryWrapper<RecordCourse> recordCourseQueryWrapper = new QueryWrapper<>();
            recordCourseQueryWrapper.eq("year_part", quarter.getYearPart());
            recordCourseQueryWrapper.eq("quarter", quarter.getNum());
            recordCourseQueryWrapper.eq("course_type",8);
            recordCourseQueryWrapper.eq("check_type",0);
            recordCourseQueryWrapper.le("school_date",nowDate.minusDays(minusDays));//超过7天未核对的删除
            this.remove(recordCourseQueryWrapper);
        }catch (Exception e){

        }
        return true;
    }

    /**
     * 记上课由请假改为到课或者旷课
     *
     * @return
     */
    @Override
    @Transactional
    public boolean backMoney(Long recordCoruseId) {
        try {
            RecordCourse recordCourse = recordCourseMapper.selectById(recordCoruseId);
            if (recordCourse.getIsDeductHouse().equals(0)) {
                return false;
            }
            if (!recordCourse.getIsDeductMoney().equals(0)){
                //已扣过金额不需要再扣
                return false;
            }


            QueryWrapper<RepairCourse> repairCourseQueryWrapper = new QueryWrapper<>();
            repairCourseQueryWrapper.eq("id",recordCourse.getRepairId());
            repairCourseQueryWrapper.orderByDesc("id");
            repairCourseQueryWrapper.last("limit 1");
            RepairCourse repairCourse = repairCourseMapper.selectOne(repairCourseQueryWrapper);
            if (repairCourse!=null){
                repairCourseMapper.deleteById(repairCourse);
            }

            //RecordCourseLack recordCourseLack = iRecordCourseLackService.getById(recordCoruseId);

            OrderDetail orderDetail = orderDetailMapper.selectById(recordCourse.getOrderDetailId());


            CoursePricing coursePricing = coursePricingMapper.selectById(orderDetail.getCoursePriceId());
            if (coursePricing == null) {
                return false;
            }
            //本次扣多少个课时
            BigDecimal stuDeductHour = new BigDecimal(3);

            //学生此次扣课时使用金额
            BigDecimal buckleClassMoney = coursePricing.getUnitPrice().multiply(stuDeductHour.divide(new BigDecimal(3), BigDecimal.ROUND_HALF_UP));



            if (orderDetail.getResiduePrice().compareTo(recordCourse.getBuckleClassMoney()) < 0) {
                buckleClassMoney = orderDetail.getResiduePrice();
            }
            orderDetail.setResiduePrice(orderDetail.getResiduePrice().subtract(buckleClassMoney));
            orderDetail.setUsePrice(orderDetail.getUsePrice().add(buckleClassMoney));
            orderDetailMapper.updateById(orderDetail);

            //recordCourse.setStatus(statusRecordEnum);
            recordCourse.setBuckleClassMoney(buckleClassMoney);
            recordCourse.setTeacherGetHouse(recordCourse.getTeacherGetHouse());
            recordCourse.setTeacherGetMoney(recordCourse.getTeacherGetMoney());
            recordCourse.setIsDeductHouse(1);
            recordCourse.setIsDeductMoney(1);
            //recordCourse.setReachType(ReachTypeEnum.LATE);//手动改为到课，为迟到
            recordCourse.setOrderDetailId(recordCourse.getOrderDetailId());
           /* CourseSchedulingDetail courseSchedulingDetail = iCourseSchedulingDetailService.getById(recordCourse.getSchedulingDetailId());
            if (courseSchedulingDetail == null) {
                RepairCourse repairCourse = repairCourseMapper.selectById(recordCourse.getSchedulingDetailId());
                if (repairCourse != null) {
                    recordCourse.setUseLeaveNum(repairCourse.getUseLeaveNum());
                }
            } else {
                recordCourse.setUseLeaveNum(courseSchedulingDetail.getUseLeaveNum());
            }*/

            recordCourseMapper.updateById(recordCourse);

            QueryWrapper<RecordCost> recordCostUpdateWrapper = new QueryWrapper<>();
            recordCostUpdateWrapper.eq("record_course_id", recordCourse.getId());
            recordCostUpdateWrapper.last("limit 1");
            RecordCost recordCost = iRecordCostService.getOne(recordCostUpdateWrapper);

            //recordCost.setOrderDetailId(recordCourseLack.getOrderDetailId());
            //recordCost.setRecordCourseId(recordCourse.getId());
            recordCost.setBuckleClassMoney(buckleClassMoney);
            recordCost.setTeacherGetHouse(recordCourse.getTeacherGetHouse());
            recordCost.setTeacherGetMoney(recordCourse.getTeacherGetMoney());
            iRecordCostService.updateById(recordCost);
            iRecordCourseLackService.removeById(recordCourse.getId());

            return true;
        }catch (Exception e){
            System.out.println("jjjjjj:"+e.getMessage());
        }
        return true;
    }


    /**
     * 处理超时未补的扣金额
     * @return
     */
    @Override
    public boolean disposeTimeoutNotRepair(){
        LocalDate nowDate = LocalDate.now();
        Quarter quarter = iQuarterService.getNowQuarter();
        //学期班
        if (quarter.getType().equals(1)){
            List<RecordCourse> recordCourseList = recordCourseMapper.getTimeoutNotRepair(quarter.getYearPart(),quarter.getNum(),1,nowDate.toString());
            for (RecordCourse recordCourse : recordCourseList) {
                QueryWrapper<RecordBackDateSet> recordBackDateSetQueryWrapper = new QueryWrapper<>();
                recordBackDateSetQueryWrapper.eq("record_course_id",recordCourse.getId());
                recordBackDateSetQueryWrapper.orderByDesc("id");
                recordBackDateSetQueryWrapper.last("limit 1");
                RecordBackDateSet recordBackDateSet = iRecordBackDateSetService.getOne(recordBackDateSetQueryWrapper);
                //没有特殊要求设置
                if (Objects.isNull(recordBackDateSet)){
                    this.backMoney(recordCourse.getId());
                }else {
                    if (nowDate.isAfter(recordBackDateSet.getBackDate()) || nowDate.equals(recordBackDateSet.getBackDate())){
                        this.backMoney(recordCourse.getId());
                    }
                }
            }
        }
        return true;
    }

    @Override
    public Integer getMaxTaskLesson(Integer YearPart, Integer QuarterNum, String SubjectsId,Long courseVersionId,Integer categoryId){
        Integer tastMaxLessonNum = 20;
        try {
            if (SubjectsId.equals("2")){
                tastMaxLessonNum = iMathematicsFeignClient.getTaskNowMaxLessonNum(YearPart.toString(),QuarterNum.toString(),SubjectsId,courseVersionId,categoryId);
            }else if (SubjectsId.equals("3")){
                tastMaxLessonNum = iPhysicsFeignClient.getTaskNowMaxLessonNum(YearPart.toString(),QuarterNum.toString(),SubjectsId,courseVersionId,categoryId);
            }
        }catch (Exception e){}
        return tastMaxLessonNum;
    }
}
